fix(tfstated): add delete handler tests

This commit is contained in:
Julien Dessaux 2024-10-05 09:54:35 +02:00
parent 7ec826921c
commit c4ce5e8623
Signed by: adyxax
GPG key ID: F92E51B86E07177E
3 changed files with 58 additions and 13 deletions

View file

@ -1,8 +1,6 @@
package main package main
import ( import (
"database/sql"
"errors"
"fmt" "fmt"
"net/http" "net/http"
@ -17,15 +15,13 @@ func handleDelete(db *database.DB) http.Handler {
return return
} }
if err := db.DeleteState(r.URL.Path); err != nil { if success, err := db.DeleteState(r.URL.Path); err != nil {
if errors.Is(err, sql.ErrNoRows) { _ = errorResponse(w, http.StatusInternalServerError, err)
} else if success {
w.WriteHeader(http.StatusOK)
} else {
_ = errorResponse(w, http.StatusNotFound, _ = errorResponse(w, http.StatusNotFound,
fmt.Errorf("state path not found: %s", r.URL.Path)) fmt.Errorf("state path not found: %s", r.URL.Path))
} else {
_ = errorResponse(w, http.StatusInternalServerError, err)
}
} else {
w.WriteHeader(http.StatusOK)
} }
}) })
} }

View file

@ -0,0 +1,41 @@
package main
import (
"io"
"net/http"
"net/url"
"strings"
"testing"
)
func TestDelete(t *testing.T) {
tests := []struct {
method string
uri *url.URL
body io.Reader
expect string
status int
msg string
}{
{"DELETE", &url.URL{Path: "/"}, nil, "", http.StatusBadRequest, "/"},
{"DELETE", &url.URL{Path: "/non_existent_delete"}, nil, "", http.StatusNotFound, "non existent"},
{"POST", &url.URL{Path: "/test_delete"}, strings.NewReader("the_test_delete"), "", http.StatusOK, "/test_delete"},
{"DELETE", &url.URL{Path: "/test_delete"}, nil, "", http.StatusOK, "/test_delete"},
{"DELETE", &url.URL{Path: "/test_delete"}, nil, "", http.StatusNotFound, "/test_delete"},
}
for _, tt := range tests {
runHTTPRequest(tt.method, tt.uri, tt.body, func(r *http.Response, err error) {
if err != nil {
t.Fatalf("failed %s with error: %+v", tt.method, err)
} else if r.StatusCode != tt.status {
t.Fatalf("%s %s should %s, got %s", tt.method, tt.msg, http.StatusText(tt.status), http.StatusText(r.StatusCode))
} else if tt.expect != "" {
if body, err := io.ReadAll(r.Body); err != nil {
t.Fatalf("failed to read body with error: %+v", err)
} else if strings.Compare(string(body), tt.expect) != 0 {
t.Fatalf("%s should have returned \"%s\", got %s", tt.method, tt.expect, string(body))
}
}
})
}
}

View file

@ -5,9 +5,17 @@ import (
"fmt" "fmt"
) )
func (db *DB) DeleteState(name string) error { // returns true in case of successful deletion
_, err := db.Exec(`DELETE FROM states WHERE name = ?;`, name) func (db *DB) DeleteState(name string) (bool, error) {
return err result, err := db.Exec(`DELETE FROM states WHERE name = ?;`, name)
if err != nil {
return false, err
}
n, err := result.RowsAffected()
if err != nil {
return false, err
}
return n == 1, nil
} }
func (db *DB) GetState(name string) ([]byte, error) { func (db *DB) GetState(name string) ([]byte, error) {