diff --git a/ballot/GetCandidatesVote_152da079ca_test.go b/ballot/GetCandidatesVote_152da079ca_test.go new file mode 100644 index 0000000..418fd59 --- /dev/null +++ b/ballot/GetCandidatesVote_152da079ca_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "sync" + "testing" +) + +var once sync.Once +var candidateVotesStore map[string]int + +func getCandidatesVote() map[string]int { + once.Do(func() { + candidateVotesStore = make(map[string]int) + }) + return candidateVotesStore +} + +func TestGetCandidatesVote_152da079ca(t *testing.T) { + // Test case 1: Check if the function returns a non-nil map + votes := getCandidatesVote() + if votes == nil { + t.Error("Expected a non-nil map, but got nil") + } + + // Test case 2: Check if the map is empty + if len(votes) != 0 { + t.Errorf("Expected an empty map, but got a map of length %d", len(votes)) + } + + // Test case 3: Check if the function returns the same map on subsequent calls + votes["candidate1"] = 10 + votes2 := getCandidatesVote() + if len(votes2) != 1 { + t.Errorf("Expected a map of length 1, but got a map of length %d", len(votes2)) + } + if votes2["candidate1"] != 10 { + t.Errorf("Expected candidate1 to have 10 votes, but got %d votes", votes2["candidate1"]) + } +} diff --git a/ballot/HttpClientRequest_8fc45b1eff_test.go b/ballot/HttpClientRequest_8fc45b1eff_test.go new file mode 100644 index 0000000..6714549 --- /dev/null +++ b/ballot/HttpClientRequest_8fc45b1eff_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "bytes" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func httpClientRequest(method, url, path string, body *bytes.Buffer) (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_8fc45b1eff(t *testing.T) { + t.Run("success case", func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + rw.Write([]byte(`OK`)) + })) + defer server.Close() + + statusCode, body, err := httpClientRequest("GET", server.URL, "/", nil) + if err != nil { + t.Errorf("Expected no error, but got: %v", err) + } + + if statusCode != http.StatusOK { + t.Errorf("Expected status code %d, but got: %d", http.StatusOK, statusCode) + } + + if string(body) != "OK" { + t.Errorf("Expected body %s, but got: %s", "OK", string(body)) + } + }) + + t.Run("failure case", func(t *testing.T) { + _, _, err := httpClientRequest("GET", "http://invalid-url", "/", nil) + if err == nil { + t.Error("Expected error, but got none") + } + + if !strings.Contains(err.Error(), "no such host") { + t.Errorf("Expected error message to contain %q, but got: %v", "no such host", err) + } + }) +} diff --git a/ballot/RunTest_13039fcb01_test.go b/ballot/RunTest_13039fcb01_test.go new file mode 100644 index 0000000..14b16e7 --- /dev/null +++ b/ballot/RunTest_13039fcb01_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "bytes" + "errors" + "fmt" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +type Status struct { + Code int + Message string +} + +type BallotTest func(t *testing.T) error + +var TestBallot BallotTest = func(t *testing.T) error { + // TODO: Add your test logic here + return nil +} + +func writeVoterResponse(w http.ResponseWriter, status Status) { + // TODO: Add your logic here +} + +func runTest(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Content-Type", "application/json") + defer r.Body.Close() + log.Println("ballot endpoint tests running") + status := Status{} + err := TestBallot(&testing.T{}) + if err != nil { + status.Message = fmt.Sprintf("Test Cases Failed with error : %v", err) + status.Code = http.StatusBadRequest + } + status.Message = "Test Cases passed" + status.Code = http.StatusOK + writeVoterResponse(w, status) +} + +func TestRunTest_13039fcb01(t *testing.T) { + req, err := http.NewRequest("POST", "/test", bytes.NewBuffer([]byte(`test`))) + 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 := `{"Code":200,"Message":"Test Cases passed"}` + if rr.Body.String() != expected { + t.Errorf("handler returned unexpected body: got %v want %v", + rr.Body.String(), expected) + } +} + +func TestRunTest_13039fcb01_Failure(t *testing.T) { + req, err := http.NewRequest("POST", "/test", bytes.NewBuffer([]byte(`test`))) + if err != nil { + t.Fatal(err) + } + rr := httptest.NewRecorder() + handler := http.HandlerFunc(runTest) + + // Mocking TestBallot to return error + TestBallot = func(t *testing.T) error { + return errors.New("mock error") + } + + 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 := `{"Code":400,"Message":"Test Cases Failed with error : mock error"}` + if rr.Body.String() != expected { + t.Errorf("handler returned unexpected body: got %v want %v", + rr.Body.String(), expected) + } +} diff --git a/ballot/SaveVote_3a682778fa_test.go b/ballot/SaveVote_3a682778fa_test.go new file mode 100644 index 0000000..39a0311 --- /dev/null +++ b/ballot/SaveVote_3a682778fa_test.go @@ -0,0 +1,55 @@ +package main + +import ( + "testing" +) + +type Vote struct { + CandidateID string +} + +var candidateVotesStore map[string]int + +func getCandidatesVote() map[string]int { + if candidateVotesStore == nil { + candidateVotesStore = make(map[string]int) + } + return candidateVotesStore +} + +func saveVote(vote Vote) error { + candidateVotesStore = getCandidatesVote() + candidateVotesStore[vote.CandidateID]++ + return nil +} + +func TestSaveVote_3a682778fa(t *testing.T) { + vote := Vote{CandidateID: "candidate1"} + err := saveVote(vote) + if err != nil { + t.Error("Failed to save vote") + } + + if candidateVotesStore[vote.CandidateID] != 1 { + t.Error("Vote count mismatch") + } + + vote2 := Vote{CandidateID: "candidate2"} + err = saveVote(vote2) + if err != nil { + t.Error("Failed to save vote") + } + + if candidateVotesStore[vote2.CandidateID] != 1 { + t.Error("Vote count mismatch") + } + + err = saveVote(vote) + if err != nil { + t.Error("Failed to save vote") + } + + if candidateVotesStore[vote.CandidateID] != 2 { + t.Error("Vote count mismatch") + } +} diff --git a/ballot/ServeRoot_e6109c0b6f_test.go b/ballot/ServeRoot_e6109c0b6f_test.go new file mode 100644 index 0000000..1bc004d --- /dev/null +++ b/ballot/ServeRoot_e6109c0b6f_test.go @@ -0,0 +1,81 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +type Vote struct { + VoterID string `json:"voterID"` + CandidateID string `json:"candidateID"` +} + +type Status struct { + Code int `json:"code"` + Message string `json:"message"` +} + +func serveRoot(w http.ResponseWriter, r *http.Request) { + // This is a placeholder function. Replace it with your actual function implementation. +} + +func TestServeRoot_e6109c0b6f(t *testing.T) { + // Test Case 1: Test GET method + 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: Test POST method with valid data + vote := &Vote{ + VoterID: "voter1", + CandidateID: "candidate1", + } + jsonVote, _ := json.Marshal(vote) + req, err = http.NewRequest("POST", "/", bytes.NewBuffer(jsonVote)) + req.Header.Set("Content-Type", "application/json") + 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: Test POST method with invalid data + req, err = http.NewRequest("POST", "/", strings.NewReader("invalid data")) + req.Header.Set("Content-Type", "application/json") + 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: Test 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_90aa96f4bb_test.go b/ballot/TestBallot_90aa96f4bb_test.go new file mode 100644 index 0000000..21c56b4 --- /dev/null +++ b/ballot/TestBallot_90aa96f4bb_test.go @@ -0,0 +1,101 @@ +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 Status struct { + Code int +} + +type Vote struct { + CandidateID string + VoterID string +} + +func httpClientRequest(method, url, path string, body io.Reader) (*http.Response, []byte, error) { + // TODO: Implement this function + return nil, nil, nil +} + +func TestBallot(t *testing.T) { + // TODO: Define port + port := "" + _, 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) + t.Error(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) + t.Error(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) + t.Error(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) + t.Error(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) + t.Error(err) + } + if postballotResp.Code != 201 { + t.Error(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) + t.Error(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) + t.Error(err) + } + if finalRespData.TotalVotes-initalRespData.TotalVotes != 1 { + t.Error(errors.New("ballot vote count error")) + } +} + +func TestTestBallot_90aa96f4bb_Failure(t *testing.T) { + // TODO: Manipulate conditions for TestBallot to fail + err := TestBallot() + if err == nil { + t.Error("TestBallot was expected to fail, but it didn't") + } else { + t.Log("TestBallot failed as expected") + } +} diff --git a/ballot/WriteVoterResponse_11f1d592d2_test.go b/ballot/WriteVoterResponse_11f1d592d2_test.go new file mode 100644 index 0000000..5521b99 --- /dev/null +++ b/ballot/WriteVoterResponse_11f1d592d2_test.go @@ -0,0 +1,72 @@ +package main + +import ( + "bytes" + "encoding/json" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +type Status struct { + Message string `json:"message"` + Code int `json:"code"` +} + +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_11f1d592d2(t *testing.T) { + t.Run("Success Case", func(t *testing.T) { + req, err := http.NewRequest("GET", "/vote", nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + writeVoterResponse(w, Status{Message: "Success", Code: 200}) + }) + + 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":"Success","code":200}` + if rr.Body.String() != expected { + t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) + } + }) + + t.Run("Error Case", func(t *testing.T) { + req, err := http.NewRequest("GET", "/vote", nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + writeVoterResponse(w, Status{Message: "Error", Code: 500}) + }) + + 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":"Error","code":500}` + if rr.Body.String() != expected { + t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) + } + }) +} 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