Moved unit test files inside same directory as test target

The unit tests were inside the `gateway/tests` directory which had no
effect to the coverage for `go test`. Therefore, moved the tests inside
the same directory as the test target.

Signed-off-by: Ken Fukuyama <kenfdev@gmail.com>
This commit is contained in:
Ken Fukuyama
2018-04-05 23:29:11 +09:00
committed by Alex Ellis
parent 5429df1e98
commit e6a6aea422
9 changed files with 71 additions and 155 deletions

View File

@ -1,104 +0,0 @@
package tests
import (
"encoding/json"
"log"
"net/http"
"net/http/httptest"
"testing"
"github.com/openfaas/faas/gateway/metrics"
"github.com/openfaas/faas/gateway/requests"
)
type FakePrometheusQueryFetcher struct {
}
func (q FakePrometheusQueryFetcher) Fetch(query string) (*metrics.VectorQueryResponse, error) {
val := []byte(`{"status":"success","data":{"resultType":"vector","result":[{"metric":{"code":"200","function_name":"func_echoit"},"value":[1509267827.752,"1"]}]}}`)
queryRes := metrics.VectorQueryResponse{}
err := json.Unmarshal(val, &queryRes)
return &queryRes, err
}
func makeFakePrometheusQueryFetcher() FakePrometheusQueryFetcher {
return FakePrometheusQueryFetcher{}
}
func Test_PrometheusMetrics_MixedInto_Services(t *testing.T) {
functionsHandler := makeFunctionsHandler()
fakeQuery := makeFakePrometheusQueryFetcher()
handler := metrics.AddMetricsHandler(functionsHandler, fakeQuery)
rr := httptest.NewRecorder()
request, _ := http.NewRequest(http.MethodGet, "/system/functions", nil)
handler.ServeHTTP(rr, request)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}
if rr.Header().Get("Content-Type") != "application/json" {
t.Errorf("Want application/json content-type, got: %s", rr.Header().Get("Content-Type"))
}
body := rr.Body.String()
if len(body) == 0 {
t.Errorf("Want content-length > 0, got: %d", len(rr.Body.String()))
}
results := []requests.Function{}
json.Unmarshal([]byte(rr.Body.String()), &results)
if len(results) == 0 {
t.Errorf("Want %d function, got: %d", 1, len(results))
}
if results[0].InvocationCount != 1 {
t.Errorf("InvocationCount want: %d , got: %f", 1, results[0].InvocationCount)
}
}
func Test_FunctionsHandler_ReturnsJSONAndOneFunction(t *testing.T) {
functionsHandler := makeFunctionsHandler()
rr := httptest.NewRecorder()
request, err := http.NewRequest(http.MethodGet, "/system/functions", nil)
if err != nil {
t.Fatal(err)
}
functionsHandler.ServeHTTP(rr, request)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}
if rr.Header().Get("Content-Type") != "application/json" {
t.Errorf("Want application/json content-type, got: %s", rr.Header().Get("Content-Type"))
}
if len(rr.Body.String()) == 0 {
t.Errorf("Want content-length > 0, got: %d", len(rr.Body.String()))
}
}
func makeFunctionsHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
functions := []requests.Function{
requests.Function{
Name: "func_echoit",
Replicas: 0,
},
}
bytesOut, marshalErr := json.Marshal(&functions)
if marshalErr != nil {
log.Fatal(marshalErr.Error())
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, err := w.Write(bytesOut)
if err != nil {
log.Fatal(err)
}
}
}

View File

@ -1,55 +0,0 @@
// Copyright (c) Alex Ellis 2017. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package tests
import (
"testing"
"github.com/openfaas/faas/gateway/handlers"
)
func TestScale1to5(t *testing.T) {
minReplicas := uint64(1)
newReplicas := handlers.CalculateReplicas("firing", 1, handlers.DefaultMaxReplicas, minReplicas)
if newReplicas != 5 {
t.Log("Expected increment in blocks of 5 from 1 to 5")
t.Fail()
}
}
func TestScale5to10(t *testing.T) {
minReplicas := uint64(1)
newReplicas := handlers.CalculateReplicas("firing", 5, handlers.DefaultMaxReplicas, minReplicas)
if newReplicas != 10 {
t.Log("Expected increment in blocks of 5 from 5 to 10")
t.Fail()
}
}
func TestScaleCeilingOf20Replicas_Noaction(t *testing.T) {
minReplicas := uint64(1)
newReplicas := handlers.CalculateReplicas("firing", 20, handlers.DefaultMaxReplicas, minReplicas)
if newReplicas != 20 {
t.Log("Expected ceiling of 20 replicas")
t.Fail()
}
}
func TestScaleCeilingOf20Replicas(t *testing.T) {
minReplicas := uint64(1)
newReplicas := handlers.CalculateReplicas("firing", 19, handlers.DefaultMaxReplicas, minReplicas)
if newReplicas != 20 {
t.Log("Expected ceiling of 20 replicas")
t.Fail()
}
}
func TestBackingOff10to1(t *testing.T) {
minReplicas := uint64(1)
newReplicas := handlers.CalculateReplicas("resolved", 10, handlers.DefaultMaxReplicas, minReplicas)
if newReplicas != 1 {
t.Log("Expected backing off to 1 replica")
t.Fail()
}
}

View File

@ -1,24 +0,0 @@
{
"session": {
"sessionId": "SessionId.ea96e58d-dc16-43e1-b238-daac4541110c",
"application": {
"applicationId": "amzn1.ask.skill.72fb1025-aacc-4d05-a582-21344940c023"
},
"attributes": {},
"user": {
"userId": "amzn1.ask.account.AEN7KA5DBXAAWQPDUXTXFWBARZ5YZ6TNOQR5CUMV5LCCJTMBZVFP45SZVLGDD5GQBOM7QMELRS7LHG3F2FN2QQQMTBURDL5I4PQ33EHMNNGO4TXWG732Y6SDM2YZKHSPWIIWBH3GSE3Q3TTFAYN2Y66RHBKRANYCNMX2WORMASUGVRHUNBB4HZMJEC7HQDWUSXAOMP77WGJU4AY"
},
"new": true
},
"request": {
"type": "IntentRequest",
"requestId": "EdwRequestId.a934104e-3282-4620-b056-4aa4c5995503",
"locale": "en-GB",
"timestamp": "2016-12-07T15:50:01Z",
"intent": {
"name": "HostnameIntent",
"slots": {}
}
},
"version": "1.0"
}

View File

@ -1,201 +0,0 @@
// Copyright (c) Alex Ellis 2017. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package tests
import (
"testing"
"time"
"github.com/openfaas/faas/gateway/types"
)
type EnvBucket struct {
Items map[string]string
}
func NewEnvBucket() EnvBucket {
return EnvBucket{
Items: make(map[string]string),
}
}
func (e EnvBucket) Getenv(key string) string {
return e.Items[key]
}
func (e EnvBucket) Setenv(key string, value string) {
e.Items[key] = value
}
func TestRead_UseExternalProvider_Defaults(t *testing.T) {
defaults := NewEnvBucket()
readConfig := types.ReadConfig{}
config := readConfig.Read(defaults)
if config.UseExternalProvider() != false {
t.Log("Default for UseExternalProvider should be false")
t.Fail()
}
if config.DirectFunctions != false {
t.Log("Default for DirectFunctions should be false")
t.Fail()
}
if len(config.DirectFunctionsSuffix) > 0 {
t.Log("Default for DirectFunctionsSuffix should be empty as a default")
t.Fail()
}
}
func TestRead_DirectFunctionsOverride(t *testing.T) {
defaults := NewEnvBucket()
readConfig := types.ReadConfig{}
defaults.Setenv("direct_functions", "true")
wantSuffix := "openfaas-fn.cluster.local.svc."
defaults.Setenv("direct_functions_suffix", wantSuffix)
config := readConfig.Read(defaults)
if config.DirectFunctions != true {
t.Logf("DirectFunctions should be true, got: %v", config.DirectFunctions)
t.Fail()
}
if config.DirectFunctionsSuffix != wantSuffix {
t.Logf("DirectFunctionsSuffix want: %s, got: %s", wantSuffix, config.DirectFunctionsSuffix)
t.Fail()
}
}
func TestRead_EmptyTimeoutConfig(t *testing.T) {
defaults := NewEnvBucket()
readConfig := types.ReadConfig{}
config := readConfig.Read(defaults)
if (config.ReadTimeout) != time.Duration(8)*time.Second {
t.Log("ReadTimeout incorrect")
t.Fail()
}
if (config.WriteTimeout) != time.Duration(8)*time.Second {
t.Log("WriteTimeout incorrect")
t.Fail()
}
}
func TestRead_ReadAndWriteTimeoutConfig(t *testing.T) {
defaults := NewEnvBucket()
defaults.Setenv("read_timeout", "10")
defaults.Setenv("write_timeout", "60")
readConfig := types.ReadConfig{}
config := readConfig.Read(defaults)
if (config.ReadTimeout) != time.Duration(10)*time.Second {
t.Logf("ReadTimeout incorrect, got: %d\n", config.ReadTimeout)
t.Fail()
}
if (config.WriteTimeout) != time.Duration(60)*time.Second {
t.Logf("WriteTimeout incorrect, got: %d\n", config.WriteTimeout)
t.Fail()
}
}
func TestRead_ReadAndWriteTimeoutDurationConfig(t *testing.T) {
defaults := NewEnvBucket()
defaults.Setenv("read_timeout", "20s")
defaults.Setenv("write_timeout", "1m30s")
readConfig := types.ReadConfig{}
config := readConfig.Read(defaults)
if (config.ReadTimeout) != time.Duration(20)*time.Second {
t.Logf("ReadTimeout incorrect, got: %d\n", config.ReadTimeout)
t.Fail()
}
if (config.WriteTimeout) != time.Duration(90)*time.Second {
t.Logf("WriteTimeout incorrect, got: %d\n", config.WriteTimeout)
t.Fail()
}
}
func TestRead_UseNATSDefaultsToOff(t *testing.T) {
defaults := NewEnvBucket()
readConfig := types.ReadConfig{}
config := readConfig.Read(defaults)
if config.UseNATS() == true {
t.Log("NATS is supposed to be off by default")
t.Fail()
}
}
func TestRead_UseNATS(t *testing.T) {
defaults := NewEnvBucket()
defaults.Setenv("faas_nats_address", "nats")
defaults.Setenv("faas_nats_port", "6222")
readConfig := types.ReadConfig{}
config := readConfig.Read(defaults)
if config.UseNATS() == false {
t.Log("NATS was requested in config, but not enabled.")
t.Fail()
}
}
func TestRead_UseNATSBadPort(t *testing.T) {
defaults := NewEnvBucket()
defaults.Setenv("faas_nats_address", "nats")
defaults.Setenv("faas_nats_port", "6fff")
readConfig := types.ReadConfig{}
config := readConfig.Read(defaults)
if config.UseNATS() == true {
t.Log("NATS had bad config, should not be enabled.")
t.Fail()
}
}
func TestRead_PrometheusNonDefaults(t *testing.T) {
defaults := NewEnvBucket()
defaults.Setenv("faas_prometheus_host", "prom1")
defaults.Setenv("faas_prometheus_port", "9999")
readConfig := types.ReadConfig{}
config := readConfig.Read(defaults)
if config.PrometheusHost != "prom1" {
t.Logf("config.PrometheusHost, want: %s, got: %s\n", "prom1", config.PrometheusHost)
t.Fail()
}
if config.PrometheusPort != 9999 {
t.Logf("config.PrometheusHost, want: %d, got: %d\n", 9999, config.PrometheusPort)
t.Fail()
}
}
func TestRead_PrometheusDefaults(t *testing.T) {
defaults := NewEnvBucket()
readConfig := types.ReadConfig{}
config := readConfig.Read(defaults)
if config.PrometheusHost != "prometheus" {
t.Logf("config.PrometheusHost, want: %s, got: %s\n", "prometheus", config.PrometheusHost)
t.Fail()
}
if config.PrometheusPort != 9090 {
t.Logf("config.PrometheusHost, want: %d, got: %d\n", 9090, config.PrometheusPort)
t.Fail()
}
}

View File

@ -1,36 +0,0 @@
package tests
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/openfaas/faas/gateway/handlers"
)
type customHandler struct {
}
func (h customHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
func Test_HeadersAdded(t *testing.T) {
rr := httptest.NewRecorder()
handler := customHandler{}
host := "store.openfaas.com"
decorated := handlers.DecorateWithCORS(handler, host)
request, _ := http.NewRequest(http.MethodGet, "/", nil)
decorated.ServeHTTP(rr, request)
actual := rr.Header().Get("Access-Control-Allow-Origin")
if actual != host {
t.Errorf("Access-Control-Allow-Origin: want: %s got: %s", host, actual)
}
actualMethods := rr.Header().Get("Access-Control-Allow-Methods")
if actualMethods != http.MethodGet {
t.Errorf("Access-Control-Allow-Methods: want: %s got: %s", http.MethodGet, actualMethods)
}
}

View File

@ -1,75 +0,0 @@
package tests
import (
"net/http"
"testing"
"github.com/openfaas/faas/gateway/requests"
)
func TestFormattingOfURLWithPath_NoQuery(t *testing.T) {
req := requests.ForwardRequest{
RawQuery: "",
RawPath: "/encode/utf8/",
Method: http.MethodPost,
}
url := req.ToURL("markdown", 8080)
want := "http://markdown:8080/encode/utf8/"
if url != want {
t.Logf("Got: %s, want: %s", url, want)
t.Fail()
}
}
func TestFormattingOfURLAtRoot_NoQuery(t *testing.T) {
req := requests.ForwardRequest{
RawQuery: "",
RawPath: "/",
Method: http.MethodPost,
}
url := req.ToURL("markdown", 8080)
want := "http://markdown:8080/"
if url != want {
t.Logf("Got: %s, want: %s", url, want)
t.Fail()
}
}
// experimental test
// func TestMyURL(t *testing.T) {
// v, _ := url.Parse("http://markdown/site?query=test")
// t.Logf("RequestURI %s", v.RequestURI())
// t.Logf("extra %s", v.Path)
// }
func TestUrlForFlask(t *testing.T) {
req := requests.ForwardRequest{
RawQuery: "query=uptime",
RawPath: "/function/flask",
Method: http.MethodPost,
}
url := req.ToURL("flask", 8080)
want := "http://flask:8080/function/flask?query=uptime"
if url != want {
t.Logf("Got: %s, want: %s", url, want)
t.Fail()
}
}
func TestFormattingOfURL_OneQuery(t *testing.T) {
req := requests.ForwardRequest{
RawQuery: "name=alex",
RawPath: "/",
Method: http.MethodPost,
}
url := req.ToURL("flask", 8080)
want := "http://flask:8080/?name=alex"
if url != want {
t.Logf("Got: %s, want: %s", url, want)
t.Fail()
}
}

View File

@ -1,47 +0,0 @@
{
"receiver": "scale-up",
"status": "firing",
"alerts": [{
"status": "firing",
"labels": {
"alertname": "APIHighInvocationRate",
"code": "200",
"function_name": "func_nodeinfo",
"instance": "gateway:8080",
"job": "gateway",
"monitor": "faas-monitor",
"service": "gateway",
"severity": "major",
"value": "8.998200359928017"
},
"annotations": {
"description": "High invocation total on gateway:8080",
"summary": "High invocation total on gateway:8080"
},
"startsAt": "2017-03-15T15:52:57.805Z",
"endsAt": "0001-01-01T00:00:00Z",
"generatorURL": "http://4156cb797423:9090/graph?g0.expr=rate%28gateway_function_invocation_total%5B10s%5D%29+%3E+5\u0026g0.tab=0"
}],
"groupLabels": {
"alertname": "APIHighInvocationRate",
"service": "gateway"
},
"commonLabels": {
"alertname": "APIHighInvocationRate",
"code": "200",
"function_name": "func_nodeinfo",
"instance": "gateway:8080",
"job": "gateway",
"monitor": "faas-monitor",
"service": "gateway",
"severity": "major",
"value": "8.998200359928017"
},
"commonAnnotations": {
"description": "High invocation total on gateway:8080",
"summary": "High invocation total on gateway:8080"
},
"externalURL": "http://f054879d97db:9093",
"version": "3",
"groupKey": 18195285354214864953
}

View File

@ -1,47 +0,0 @@
{
"receiver": "scale-up",
"status": "resolved",
"alerts": [{
"status": "resolved",
"labels": {
"alertname": "APIHighInvocationRate",
"code": "200",
"function_name": "func_nodeinfo",
"instance": "gateway:8080",
"job": "gateway",
"monitor": "faas-monitor",
"service": "gateway",
"severity": "major",
"value": "8.998200359928017"
},
"annotations": {
"description": "High invocation total on gateway:8080",
"summary": "High invocation total on gateway:8080"
},
"startsAt": "2017-03-15T15:52:57.805Z",
"endsAt": "2017-03-15T15:53:52.806Z",
"generatorURL": "http://4156cb797423:9090/graph?g0.expr=rate%28gateway_function_invocation_total%5B10s%5D%29+%3E+5\u0026g0.tab=0"
}],
"groupLabels": {
"alertname": "APIHighInvocationRate",
"service": "gateway"
},
"commonLabels": {
"alertname": "APIHighInvocationRate",
"code": "200",
"function_name": "func_nodeinfo",
"instance": "gateway:8080",
"job": "gateway",
"monitor": "faas-monitor",
"service": "gateway",
"severity": "major",
"value": "8.998200359928017"
},
"commonAnnotations": {
"description": "High invocation total on gateway:8080",
"summary": "High invocation total on gateway:8080"
},
"externalURL": "http://f054879d97db:9093",
"version": "3",
"groupKey": 18195285354214864953
}

View File

@ -1,45 +0,0 @@
// Copyright (c) Alex Ellis 2017. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package tests
import (
"encoding/json"
"io/ioutil"
"testing"
"github.com/openfaas/faas/gateway/requests"
)
// TestUnmarshallAlert is an exploratory test from TDD'ing the struct to parse a Prometheus alert
func TestUnmarshallAlert(t *testing.T) {
file, _ := ioutil.ReadFile("./test_alert.json")
var alert requests.PrometheusAlert
err := json.Unmarshal(file, &alert)
if err != nil {
t.Fatal(err)
}
if (len(alert.Status)) == 0 {
t.Fatal("No status read")
}
if (len(alert.Receiver)) == 0 {
t.Fatal("No status read")
}
if (len(alert.Alerts)) == 0 {
t.Fatal("No alerts read")
}
if (len(alert.Alerts[0].Labels.AlertName)) == 0 {
t.Fatal("No alerts name")
}
if (len(alert.Alerts[0].Labels.FunctionName)) == 0 {
t.Fatal("No function name read")
}
}