Skip to content

Commit

Permalink
Test suite
Browse files Browse the repository at this point in the history
  • Loading branch information
sebbalex committed Oct 13, 2019
1 parent d81dfa9 commit f09bdbb
Show file tree
Hide file tree
Showing 9 changed files with 513 additions and 21 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ require (
github.com/gorilla/mux v1.7.3
github.com/italia/publiccode-parser-go v0.0.0-20190819165358-31bf64802d87
github.com/sebbalex/go-vcsurl v0.0.0-20190821183029-e2c014ec6077
github.com/stretchr/testify v1.3.0
gopkg.in/yaml.v2 v2.2.3
)
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ github.com/alranel/go-spdx v0.0.5/go.mod h1:lcAlhyAoH9rjd33PkIx+2gsCIYwDpL4H0WX7
github.com/alranel/go-vcsurl v0.0.0-20190819164520-88a614c7acb4 h1:a+SmZVgzBVoCfNK1LPRyy/rXDn8JiA/8SpMwcaBRRO0=
github.com/alranel/go-vcsurl v0.0.0-20190819164520-88a614c7acb4/go.mod h1:tp+e312yiwgu8H4/Ly26J8MevK9lz7BucU4PPlEv0ag=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/deadcheat/goblet v1.3.1 h1:OPOYQjHlbPmG8fFCt8GNNGECLVhaJ0n7F7cP5Mh7G/A=
github.com/deadcheat/goblet v1.3.1/go.mod h1:IrMNyAwyrVgB30HsND2WgleTUM4wHTS9m40yNY6NJQg=
Expand All @@ -20,11 +21,13 @@ github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw=
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/italia/publiccode-parser-go v0.0.0-20190819165358-31bf64802d87 h1:7KH+erTBwZAvxnwuSHMmNQSyppY1Ol77hOYYQuhKqCw=
github.com/italia/publiccode-parser-go v0.0.0-20190819165358-31bf64802d87/go.mod h1:q18a0jHIXgRVNJ12lI5mBHnVlhqLcUdQ2a3888PhTqY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sebbalex/go-vcsurl v0.0.0-20190821183029-e2c014ec6077 h1:G6sZr8RQ9Sfph8umeO+K4Z63lI0VkE/6e320pZExppQ=
github.com/sebbalex/go-vcsurl v0.0.0-20190821183029-e2c014ec6077/go.mod h1:kjPbS94KyBQo2epWbw3fSBSUz+pbpODf9QYPWlShy1A=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/thoas/go-funk v0.4.0 h1:KBaa5NL7NMtsFlQaD8nQMbDt1wuM+OOaNQyYNYQFhVo=
github.com/thoas/go-funk v0.4.0/go.mod h1:mlR+dHGb+4YgXkf13rkQTuzrneeHANxOm6+ZnEV9HsA=
Expand Down
40 changes: 40 additions & 0 deletions src/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package main

import (
"fmt"
"strings"
)

// ErrorInvalidKey represents an error caused by an invalid key.
type ErrorInvalidKey struct {
Key string
}

func (e ErrorInvalidKey) Error() string {
return fmt.Sprintf("invalid key: %s", e.Key)
}

// ErrorInvalidValue represents an error caused by an invalid value.
type ErrorInvalidValue struct {
Key string
Reason string
}

func (e ErrorInvalidValue) Error() string {
return fmt.Sprintf("%s: %s", e.Key, e.Reason)
}

func newErrorInvalidValue(key string, reason string, args ...interface{}) ErrorInvalidValue {
return ErrorInvalidValue{Key: key, Reason: fmt.Sprintf(reason, args...)}
}

// ErrorParseMulti represents an error caused by a multivalue key.
type ErrorParseMulti []error

func (es ErrorParseMulti) Error() string {
var ss []string
for _, e := range es {
ss = append(ss, e.Error())
}
return strings.Join(ss, "\n")
}
7 changes: 5 additions & 2 deletions src/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,10 +195,13 @@ func (app *App) validate(w http.ResponseWriter, r *http.Request) {
log.Printf("Error converting: %v", errConverting)
}
if errParse != nil {
log.Printf("Error parsing: %v", errParse)
// log.Printf("Error parsing: %v", errParse)
w.Header().Set("Content-type", "application/json")
w.WriteHeader(http.StatusUnprocessableEntity)
json.NewEncoder(w).Encode(errParse)

json, _ := json.Marshal(errParse)
w.Write(json)
// json.NewEncoder(w).Encode(errParse)
} else {
//set response CT based on client accept header
//and return respectively content
Expand Down
120 changes: 101 additions & 19 deletions src/main_test.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,42 @@
package main

import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

var app App

type Es []ErrorInvalidValue

func (a Es) Len() int { return len(a) }
func (a Es) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a Es) Less(i, j int) bool { return a[i].Key < a[j].Key }

func TestMain(m *testing.M) {
app = App{}
app.init()
code := m.Run()
os.Exit(code)
}

func TestGitHub(t *testing.T) {
url, _ := url.Parse("https://github.com/sebbalex/pc-web-validator")
AssertEqual(t, getRawURL(url), "https://raw.githubusercontent.com/sebbalex/pc-web-validator/master/")
assert.Equal(t, getRawURL(url), "https://raw.githubusercontent.com/sebbalex/pc-web-validator/master/")

url, _ = url.Parse("https://github.com/sebbalex/pc-web-validator.git")
AssertEqual(t, getRawURL(url), "https://raw.githubusercontent.com/sebbalex/pc-web-validator/master/")
assert.Equal(t, getRawURL(url), "https://raw.githubusercontent.com/sebbalex/pc-web-validator/master/")
}

func TestConversion(t *testing.T) {
Expand All @@ -27,25 +47,87 @@ func TestConversion(t *testing.T) {
}
yml, err := ioutil.ReadAll(fileYML)
json, err := ioutil.ReadAll(fileJSON)
AssertEqual(t, string(yaml2json(yml)), strings.TrimSpace(string(json)))
assert.Equal(t, string(yaml2json(yml)), strings.TrimSpace(string(json)))
}

func TestValidationZeroPayload(t *testing.T) {
req, _ := http.NewRequest("POST", "/pc/validate?disableNetwork=true", nil)
response := executeRequest(req)
checkResponseCode(t, http.StatusOK, response.Code)
if body := response.Body.String(); body != "" {
t.Errorf("Expected an message. Got %s", body)
}
}

func TestValidationErrWithNoNetwork(t *testing.T) {
var errs []ErrorInvalidValue //[]map[string]interface{}
var errOut []ErrorInvalidValue //[]map[string]interface{}

fileYML, err := os.Open("../tests/missing_maintenance_contacts.yml")
if err != nil {
log.Fatal(err)
}
out, err := ioutil.ReadFile("../tests/invalid_out.log")
if err != nil {
log.Fatal(err)
}
req, _ := http.NewRequest("POST", "/pc/validate?disableNetwork=false", fileYML)
response := executeRequest(req)
err = json.Unmarshal(out, &errOut)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(response.Body.Bytes(), &errs)
if err != nil {
log.Fatal(err)
}
sort.Sort(Es(errs))
sort.Sort(Es(errOut))
assert.Equal(t, errs, errOut)
}

// AssertEqual checks if values are equal
func AssertEqual(t *testing.T, a interface{}, b interface{}) {
if a == b {
return
func TestValidationWithNoNetwork(t *testing.T) {
checks := []bool{true, false}
for _, check := range checks {
fileYML, err := os.Open("../tests/valid.minimal.yml")
if err != nil {
log.Fatal(err)
}
out, err := ioutil.ReadFile("../tests/valid.minimal.out.yml")
if err != nil {
log.Fatal(err)
}
req, _ := http.NewRequest("POST", "/pc/validate?disableNetwork="+strconv.FormatBool(check), fileYML)
response := executeRequest(req)
checkResponseCode(t, http.StatusOK, response.Code)
assert.Equal(t, string(out), response.Body.String())
}
// debug.PrintStack()
_, fn, line, _ := runtime.Caller(1)
t.Errorf("%s:%d: Received %v (type %v), expected %v (type %v)", fn, line, a, reflect.TypeOf(a), b, reflect.TypeOf(b))
}

// AssertNil checks if a value is nil
func AssertNil(t *testing.T, a interface{}) {
if reflect.ValueOf(a).IsNil() {
return
func TestValidationWithNetwork(t *testing.T) {
fileYML, err := os.Open("../tests/valid.minimal.yml")
if err != nil {
log.Fatal(err)
}
out, err := ioutil.ReadFile("../tests/valid.minimal.out.yml")
if err != nil {
log.Fatal(err)
}
req, _ := http.NewRequest("POST", "/pc/validate", fileYML)
response := executeRequest(req)
checkResponseCode(t, http.StatusOK, response.Code)
assert.Equal(t, string(out), response.Body.String())
}

// Utility functions to make mock request and check response
func executeRequest(req *http.Request) *httptest.ResponseRecorder {
rr := httptest.NewRecorder()
app.Router.ServeHTTP(rr, req)

return rr
}
func checkResponseCode(t *testing.T, expected, actual int) {
if expected != actual {
t.Errorf("Expected response code %d. Got %d\n", expected, actual)
}
//debug.PrintStack()
_, fn, line, _ := runtime.Caller(1)
t.Errorf("%s:%d: Received %v (type %v), expected nil", fn, line, a, reflect.TypeOf(a))
}
Loading

0 comments on commit f09bdbb

Please sign in to comment.