From 6e00f7535eedf4ecb0aa374104b3d10ce14c3710 Mon Sep 17 00:00:00 2001 From: roostAI <108646238+roostAI@users.noreply.github.com> Date: Tue, 15 Aug 2023 13:25:17 +0000 Subject: [PATCH] Test generated by RoostGPT for test zb-test using AI Type Open AI and AI Model gpt-4 --- ballot/GetCandidatesVote_5ba0d06cb0_test.go | 46 +++++++ ballot/HttpClientRequest_a374070552_test.go | 118 ++++++++++++++++ ballot/RunTest_a2bb790205_test.go | 55 ++++++++ ballot/SaveVote_3f5729642d_test.go | 48 +++++++ ballot/ServeRoot_da512bfd0e_test.go | 101 ++++++++++++++ ballot/TestBallot_846a5695f2_test.go | 138 +++++++++++++++++++ ballot/WriteVoterResponse_6201595a70_test.go | 61 ++++++++ ballot/go.mod | 3 + 8 files changed, 570 insertions(+) create mode 100644 ballot/GetCandidatesVote_5ba0d06cb0_test.go create mode 100644 ballot/HttpClientRequest_a374070552_test.go create mode 100644 ballot/RunTest_a2bb790205_test.go create mode 100644 ballot/SaveVote_3f5729642d_test.go create mode 100644 ballot/ServeRoot_da512bfd0e_test.go create mode 100644 ballot/TestBallot_846a5695f2_test.go create mode 100644 ballot/WriteVoterResponse_6201595a70_test.go create mode 100644 ballot/go.mod diff --git a/ballot/GetCandidatesVote_5ba0d06cb0_test.go b/ballot/GetCandidatesVote_5ba0d06cb0_test.go new file mode 100644 index 0000000..b408bda --- /dev/null +++ b/ballot/GetCandidatesVote_5ba0d06cb0_test.go @@ -0,0 +1,46 @@ +package main + +import ( + "sync" + "testing" +) + +var ( + once sync.Once + candidateVotesStore map[string]int +) + +func getCandidatesVote() map[string]int { + once.Do(func() { + candidateVotesStore = make(map[string]int) + }) + return candidateVotesStore +} + +func TestGetCandidatesVote_5ba0d06cb0(t *testing.T) { + // Test case 1: Check if the function returns an empty map on first call + votes := getCandidatesVote() + if len(votes) != 0 { + t.Error("Expected empty map on first call, got", votes) + } + + // Test case 2: Check if the function returns the same map on subsequent calls + candidateVotesStore["John"] = 5 + votes = getCandidatesVote() + if len(votes) != 1 { + t.Error("Expected map with 1 entry, got", votes) + } + if votes["John"] != 5 { + t.Error("Expected 5 votes for John, got", votes["John"]) + } + + // Test case 3: Check if the function returns the updated map after changes + candidateVotesStore["Doe"] = 10 + votes = getCandidatesVote() + if len(votes) != 2 { + t.Error("Expected map with 2 entries, got", votes) + } + if votes["Doe"] != 10 { + t.Error("Expected 10 votes for Doe, got", votes["Doe"]) + } +} diff --git a/ballot/HttpClientRequest_a374070552_test.go b/ballot/HttpClientRequest_a374070552_test.go new file mode 100644 index 0000000..8825cd3 --- /dev/null +++ b/ballot/HttpClientRequest_a374070552_test.go @@ -0,0 +1,118 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func httpClientRequest(method, url, path string, body io.Reader) (int, []byte, error) { + client := &http.Client{} + req, err := http.NewRequest(method, url+path, body) + if err != nil { + return 0, nil, err + } + resp, err := client.Do(req) + if err != nil { + return 0, nil, err + } + defer resp.Body.Close() + + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return 0, nil, err + } + return resp.StatusCode, respBody, nil +} + +func TestHttpClientRequest_a374070552(t *testing.T) { + t.Run("Successful request", func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + fmt.Fprintln(rw, "Hello, client") + })) + defer server.Close() + + statusCode, body, err := httpClientRequest("GET", server.URL, "/", nil) + if err != nil { + t.Error(err) + } + if statusCode != 200 { + t.Errorf("Expected status code 200, got %d", statusCode) + } + if !strings.Contains(string(body), "Hello, client") { + t.Errorf("Unexpected body: got %v", string(body)) + } + }) + + t.Run("Unsuccessful request - invalid operation", func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + fmt.Fprintln(rw, "Hello, client") + })) + defer server.Close() + + _, _, err := httpClientRequest("INVALID", server.URL, "/", nil) + if err == nil { + t.Error("Expected error, got nil") + } + }) + + t.Run("Unsuccessful request - invalid url", func(t *testing.T) { + _, _, err := httpClientRequest("GET", "http://invalid-url", "/", nil) + if err == nil { + t.Error("Expected error, got nil") + } + }) + + t.Run("Unsuccessful request - non 2xx status code", func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + http.Error(rw, "Bad request", http.StatusBadRequest) + })) + defer server.Close() + + statusCode, _, err := httpClientRequest("GET", server.URL, "/", nil) + if err != nil { + t.Error(err) + } + if statusCode != http.StatusBadRequest { + t.Errorf("Expected status code %d, got %d", http.StatusBadRequest, statusCode) + } + }) + + t.Run("Successful POST request with params", func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodPost { + t.Errorf("Expected method 'POST', got '%s'", req.Method) + } + + body := new(bytes.Buffer) + _, err := io.Copy(body, req.Body) + if err != nil { + t.Error(err) + } + req.Body.Close() + + if body.String() != "param1=value1¶m2=value2" { + t.Errorf("Expected body to be 'param1=value1¶m2=value2', got '%s'", body.String()) + } + + fmt.Fprintln(rw, "Hello, client") + })) + defer server.Close() + + params := strings.NewReader("param1=value1¶m2=value2") + statusCode, body, err := httpClientRequest("POST", server.URL, "/", params) + if err != nil { + t.Error(err) + } + if statusCode != 200 { + t.Errorf("Expected status code 200, got %d", statusCode) + } + if !strings.Contains(string(body), "Hello, client") { + t.Errorf("Unexpected body: got %v", string(body)) + } + }) +} diff --git a/ballot/RunTest_a2bb790205_test.go b/ballot/RunTest_a2bb790205_test.go new file mode 100644 index 0000000..7d65c1c --- /dev/null +++ b/ballot/RunTest_a2bb790205_test.go @@ -0,0 +1,55 @@ +package main + +import ( + "bytes" + "net/http" + "net/http/httptest" + "testing" +) + +func TestRunTest_a2bb790205(t *testing.T) { + t.Run("Test case passed", func(t *testing.T) { + req, err := http.NewRequest("GET", "/test", bytes.NewBuffer([]byte{})) + if err != nil { + t.Fatal(err) + } + rr := httptest.NewRecorder() + handler := http.HandlerFunc(runTest) + + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusOK { + t.Errorf("Handler returned wrong status code: got %v want %v", + status, http.StatusOK) + } + + expected := `{"Message":"Test Cases passed","Code":200}` + if rr.Body.String() != expected { + t.Errorf("Handler returned unexpected body: got %v want %v", + rr.Body.String(), expected) + } + }) + + t.Run("Test case failed", func(t *testing.T) { + req, err := http.NewRequest("GET", "/test", bytes.NewBuffer([]byte{})) + if err != nil { + t.Fatal(err) + } + rr := httptest.NewRecorder() + handler := http.HandlerFunc(runTest) + + // TODO: Make TestBallot return an error to simulate a failure + handler.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("Handler returned wrong status code: got %v want %v", + status, http.StatusBadRequest) + } + + expected := `{"Message":"Test Cases Failed with error : test error","Code":400}` + if rr.Body.String() != expected { + t.Errorf("Handler returned unexpected body: got %v want %v", + rr.Body.String(), expected) + } + }) +} diff --git a/ballot/SaveVote_3f5729642d_test.go b/ballot/SaveVote_3f5729642d_test.go new file mode 100644 index 0000000..c2530ab --- /dev/null +++ b/ballot/SaveVote_3f5729642d_test.go @@ -0,0 +1,48 @@ +package main + +import ( + "testing" +) + +// Mock Vote struct +type Vote struct { + CandidateID string +} + +// Mock candidateVotesStore +var candidateVotesStore map[string]int + +// Mock getCandidatesVote function +func getCandidatesVote() map[string]int { + return candidateVotesStore +} + +// Method to be tested +func saveVote(vote Vote) error { + candidateVotesStore = getCandidatesVote() + candidateVotesStore[vote.CandidateID]++ + return nil +} + +// Test method +func TestSaveVote_3f5729642d(t *testing.T) { + // Test case 1: When vote is saved successfully + candidateVotesStore = make(map[string]int) + vote := Vote{CandidateID: "123"} + err := saveVote(vote) + if err != nil { + t.Error("Expected nil, got ", err) + } + if candidateVotesStore[vote.CandidateID] != 1 { + t.Error("Expected 1, got ", candidateVotesStore[vote.CandidateID]) + } + + // Test case 2: When vote is saved for the second time + err = saveVote(vote) + if err != nil { + t.Error("Expected nil, got ", err) + } + if candidateVotesStore[vote.CandidateID] != 2 { + t.Error("Expected 2, got ", candidateVotesStore[vote.CandidateID]) + } +} diff --git a/ballot/ServeRoot_da512bfd0e_test.go b/ballot/ServeRoot_da512bfd0e_test.go new file mode 100644 index 0000000..078b458 --- /dev/null +++ b/ballot/ServeRoot_da512bfd0e_test.go @@ -0,0 +1,101 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" +) + +type Vote struct { + VoterID string + CandidateID string +} + +type MockSaveVote struct{} + +func (m *MockSaveVote) saveVote(vote Vote) error { + if vote.VoterID == "" || vote.CandidateID == "" { + return errors.New("Vote is not valid. Vote can not be saved") + } + return nil +} + +func serveRoot(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case "GET": + w.WriteHeader(http.StatusOK) + case "POST": + var vote Vote + err := json.NewDecoder(r.Body).Decode(&vote) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + m := MockSaveVote{} + err = m.saveVote(vote) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + w.WriteHeader(http.StatusCreated) + default: + http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) + } +} + +func TestServeRoot_da512bfd0e(t *testing.T) { + // Test case 1: Successful GET request + req, err := http.NewRequest("GET", "/", nil) + if err != nil { + t.Fatal(err) + } + rr := httptest.NewRecorder() + handler := http.HandlerFunc(serveRoot) + handler.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusOK { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) + } + + // Test case 2: Successful POST request + vote := Vote{VoterID: "voter1", CandidateID: "candidate1"} + jsonVote, _ := json.Marshal(vote) + req, err = http.NewRequest("POST", "/", bytes.NewBuffer(jsonVote)) + if err != nil { + t.Fatal(err) + } + rr = httptest.NewRecorder() + handler = http.HandlerFunc(serveRoot) + handler.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusCreated { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusCreated) + } + + // Test case 3: Unsuccessful POST request with invalid vote + vote = Vote{VoterID: "", CandidateID: ""} + jsonVote, _ = json.Marshal(vote) + req, err = http.NewRequest("POST", "/", bytes.NewBuffer(jsonVote)) + if err != nil { + t.Fatal(err) + } + rr = httptest.NewRecorder() + handler = http.HandlerFunc(serveRoot) + handler.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) + } + + // Test case 4: Unsupported method + req, err = http.NewRequest("PUT", "/", nil) + if err != nil { + t.Fatal(err) + } + rr = httptest.NewRecorder() + handler = http.HandlerFunc(serveRoot) + handler.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusMethodNotAllowed { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusMethodNotAllowed) + } +} diff --git a/ballot/TestBallot_846a5695f2_test.go b/ballot/TestBallot_846a5695f2_test.go new file mode 100644 index 0000000..23e9550 --- /dev/null +++ b/ballot/TestBallot_846a5695f2_test.go @@ -0,0 +1,138 @@ +// Test generated by RoostGPT for test zb-test using AI Type Open AI and AI Model gpt-4 + +package main + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "io/ioutil" + "log" + "math/rand" + "net" + "net/http" + "sort" + "strings" + "sync" + "testing" +) + +type Response struct { + TotalVotes int +} + +type Vote struct { + CandidateID string + VoterID string +} + +type Status struct { + Code int +} + +func TestBallot_846a5695f2(t *testing.T) { + mockServer := http.NewServeMux() + mockServer.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + json.NewEncoder(w).Encode(Response{TotalVotes: 1}) + case http.MethodPost: + json.NewEncoder(w).Encode(Status{Code: 201}) + } + }) + + server := &http.Server{ + Addr: ":8080", + Handler: mockServer, + } + + go func() { + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + t.Fatalf("Could not run server: %v", err) + } + }() + + err := testBallot() + if err != nil { + t.Errorf("testBallot() error = %v", err) + } + + server.Close() +} + +func httpClientRequest(method, url, path string, body io.Reader) (int, []byte, error) { + req, err := http.NewRequest(method, url+path, body) + if err != nil { + return 0, nil, err + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return 0, nil, err + } + defer resp.Body.Close() + + b, err := ioutil.ReadAll(resp.Body) + if err != nil { + return 0, nil, err + } + + return resp.StatusCode, b, nil +} + +func testBallot() error { + port := "8080" // TODO: Change this to the port your server is running on. + _, result, err := httpClientRequest(http.MethodGet, net.JoinHostPort("", port), "/", nil) + if err != nil { + log.Printf("Failed to get ballot count resp:%s error:%+v", string(result), err) + return err + } + log.Println("get ballot resp:", string(result)) + var initalRespData Response + if err = json.Unmarshal(result, &initalRespData); err != nil { + log.Printf("Failed to unmarshal get ballot response. %+v", err) + return err + } + + var ballotvotereq Vote + ballotvotereq.CandidateID = fmt.Sprint(rand.Intn(10)) + ballotvotereq.VoterID = fmt.Sprint(rand.Intn(10)) + reqBuff, err := json.Marshal(ballotvotereq) + if err != nil { + log.Printf("Failed to marshall post ballot request %+v", err) + return err + } + + _, result, err = httpClientRequest(http.MethodPost, net.JoinHostPort("", port), "/", bytes.NewReader(reqBuff)) + if err != nil { + log.Printf("Failed to get ballot count resp:%s error:%+v", string(result), err) + return err + } + log.Println("post ballot resp:", string(result)) + var postballotResp Status + if err = json.Unmarshal(result, &postballotResp); err != nil { + log.Printf("Failed to unmarshal post ballot response. %+v", err) + return err + } + if postballotResp.Code != 201 { + return errors.New("post ballot resp status code") + } + + _, result, err = httpClientRequest(http.MethodGet, net.JoinHostPort("", port), "/", nil) + if err != nil { + log.Printf("Failed to get final ballot count resp:%s error:%+v", string(result), err) + return err + } + log.Println("get final ballot resp:", string(result)) + var finalRespData Response + if err = json.Unmarshal(result, &finalRespData); err != nil { + log.Printf("Failed to unmarshal get final ballot response. %+v", err) + return err + } + if finalRespData.TotalVotes-initalRespData.TotalVotes != 1 { + return errors.New("ballot vote count error") + } + return nil +} diff --git a/ballot/WriteVoterResponse_6201595a70_test.go b/ballot/WriteVoterResponse_6201595a70_test.go new file mode 100644 index 0000000..7cd7449 --- /dev/null +++ b/ballot/WriteVoterResponse_6201595a70_test.go @@ -0,0 +1,61 @@ +package main + +import ( + "bytes" + "encoding/json" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +type Status struct { + Code int + Message string +} + +func writeVoterResponse(w http.ResponseWriter, status Status) { + w.Header().Set("Content-Type", "application/json") + resp, err := json.Marshal(status) + if err != nil { + log.Println("error marshaling response to vote request. error: ", err) + } + w.Write(resp) +} + +func TestWriteVoterResponse_6201595a70(t *testing.T) { + t.Run("success", func(t *testing.T) { + rr := httptest.NewRecorder() + writeVoterResponse(rr, Status{200, "Vote received"}) + + result := rr.Result() + defer result.Body.Close() + + if result.StatusCode != http.StatusOK { + t.Errorf("Expected status code %d, got %d", http.StatusOK, result.StatusCode) + } + + var status Status + json.NewDecoder(result.Body).Decode(&status) + + if status.Code != 200 || status.Message != "Vote received" { + t.Errorf("Unexpected body: got %+v", status) + } + }) + + t.Run("marshal_error", func(t *testing.T) { + rr := httptest.NewRecorder() + writeVoterResponse(rr, Status{200, string([]byte{0x80})}) + + result := rr.Result() + defer result.Body.Close() + + if result.StatusCode != http.StatusOK { + t.Errorf("Expected status code %d, got %d", http.StatusOK, result.StatusCode) + } + + if rr.Body.String() != "" { + t.Errorf("Expected empty body, got %s", rr.Body.String()) + } + }) +} diff --git a/ballot/go.mod b/ballot/go.mod new file mode 100644 index 0000000..5df022f --- /dev/null +++ b/ballot/go.mod @@ -0,0 +1,3 @@ +module ballot + +go 1.19