Skip to content

Commit

Permalink
test: Include a cluster test for Request Validator (#178)
Browse files Browse the repository at this point in the history
* test: Include a cluster test for Request Validator
  • Loading branch information
claudiachua authored Aug 2, 2022
1 parent 1d186f5 commit 3465396
Show file tree
Hide file tree
Showing 5 changed files with 134 additions and 2 deletions.
1 change: 1 addition & 0 deletions .github/workflows/test-and-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ jobs:
TWILIO_API_SECRET: ${{ secrets.TWILIO_CLUSTER_TEST_API_KEY_SECRET }}
TWILIO_FROM_NUMBER: ${{ secrets.TWILIO_FROM_NUMBER }}
TWILIO_TO_NUMBER: ${{ secrets.TWILIO_TO_NUMBER }}
TWILIO_AUTH_TOKEN: ${{ secrets.TWILIO_AUTH_TOKEN }}
run: make cluster-test

- name: Run Test Coverage
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ func main() {
]
}`

definition := make(map[string]interface{})
var definition interface{}
_ = json.Unmarshal([]byte(jsonStr), &definition)

client := twilio.NewRestClient()
Expand Down
130 changes: 129 additions & 1 deletion cluster_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,20 @@
package twilio

import (
"encoding/json"
"fmt"
"net/http"
"os"
"testing"
"time"

"github.com/localtunnel/go-localtunnel"
"github.com/stretchr/testify/assert"
twilio "github.com/twilio/twilio-go/client"
Api "github.com/twilio/twilio-go/rest/api/v2010"
ChatV2 "github.com/twilio/twilio-go/rest/chat/v2"
EventsV1 "github.com/twilio/twilio-go/rest/events/v1"
StudioV2 "github.com/twilio/twilio-go/rest/studio/v2"
)

var from string
Expand Down Expand Up @@ -120,6 +127,127 @@ func TestListParams(t *testing.T) {
assert.Nil(t, err)
}

func createValidationServer(channel chan bool) *http.Server {
server := &http.Server{}
server.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
url := r.Header["X-Forwarded-Proto"][0] + "://" + r.Header["X-Forwarded-Host"][0] + r.URL.RequestURI()
signatureHeader := r.Header["X-Twilio-Signature"]
r.ParseForm()
params := make(map[string]string)
for k, v := range r.PostForm {
params[k] = v[0]
}
requestValidator := twilio.NewRequestValidator(os.Getenv("TWILIO_AUTH_TOKEN"))
if len(signatureHeader) != 0 {
channel <- requestValidator.Validate(url, params, r.Header["X-Twilio-Signature"][0])
} else {
channel <- false
}
})
return server
}

func createStudioFlowParams(url string, method string) *StudioV2.CreateFlowParams {
jsonStr := fmt.Sprintf(`{
"description": "Studio Flow",
"states": [
{
"name": "Trigger",
"type": "trigger",
"transitions": [
{
"next": "httpRequest",
"event": "incomingRequest"
}
],
"properties": {
}
},
{
"name": "httpRequest",
"type": "make-http-request",
"transitions": [],
"properties": {
"method": "%s",
"content_type": "application/x-www-form-urlencoded;charset=utf-8",
"url": "%s"
}
}
],
"initial_state": "Trigger",
"flags": {
"allow_concurrent_calls": true
}
}`, method, url)

var definition interface{}
_ = json.Unmarshal([]byte(jsonStr), &definition)

params := &StudioV2.CreateFlowParams{
Definition: &definition,
}
params.SetFriendlyName("Go Cluster Test Flow")
params.SetStatus("published")
return params
}

func createStudioExecutionParams() *StudioV2.CreateExecutionParams {
executionParams := &StudioV2.CreateExecutionParams{}
executionParams.SetTo("To")
executionParams.SetFrom("From")
return executionParams
}

func executeFlow(t *testing.T, flowSid string) {
_, exeErr := testClient.StudioV2.CreateExecution(flowSid, createStudioExecutionParams())
if exeErr != nil {
t.Fatal("Error with Studio Execution Creation: ", exeErr)
}
}

func requestValidation(t *testing.T, method string) {
//Invoke Localtunnel
listener, ltErr := localtunnel.Listen(localtunnel.Options{})
if ltErr != nil {
t.Fatal("Error with Localtunnel: ", ltErr)
}
//Create Validation Server & Listen
channel := make(chan bool)
server := createValidationServer(channel)
go server.Serve(listener)

//Extra time for server to set up
time.Sleep(1 * time.Second)

//Create Studio Flow
params := createStudioFlowParams(listener.URL(), method)
resp, flowErr := testClient.StudioV2.CreateFlow(params)
if flowErr != nil {
t.Fatal("Error with Studio Flow Creation: ", flowErr)
}
flowSid := *resp.Sid
executeFlow(t, flowSid)

//Await for Request Validation
afterCh := time.After(5 * time.Second)
select {
case validate := <-channel:
assert.True(t, validate)
case <-afterCh:
t.Fatal("No request was sent to validation server")
}
defer testClient.StudioV2.DeleteFlow(flowSid)
defer server.Close()
}

func TestRequestValidation_GETMethod(t *testing.T) {
requestValidation(t, "GET")
}

func TestRequestValidation_POSTMethod(t *testing.T) {
requestValidation(t, "POST")
}

func TestListingAvailableNumber(t *testing.T) {
params := &Api.ListAvailablePhoneNumberTollFreeParams{}
params.SetLimit(2)
Expand All @@ -128,4 +256,4 @@ func TestListingAvailableNumber(t *testing.T) {
assert.Nil(t, err)
assert.NotNil(t, resp)
assert.Equal(t, 2, len(resp))
}
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/golang/mock v1.6.0
github.com/kr/text v0.2.0 // indirect
github.com/localtunnel/go-localtunnel v0.0.0-20170326223115-8a804488f275 // indirect
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.7.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/localtunnel/go-localtunnel v0.0.0-20170326223115-8a804488f275 h1:IZycmTpoUtQK3PD60UYBwjaCUHUP7cML494ao9/O8+Q=
github.com/localtunnel/go-localtunnel v0.0.0-20170326223115-8a804488f275/go.mod h1:zt6UU74K6Z6oMOYJbJzYpYucqdcQwSMPBEdSvGiaUMw=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
Expand Down

0 comments on commit 3465396

Please sign in to comment.