Repository: openshift-pipelines/pipelines-as-code
Pull request #282 (2021-10-11 16:29:23)

Add test for getAppToken
Signed-off-by: Chmouel Boudjnah <chmouel@redhat.com>



Patch:
diff --git a/config/403-github-push.yaml b/config/403-github-push.yaml
index 5f858c8b..2b83970a 100644
--- a/config/403-github-push.yaml
+++ b/config/403-github-push.yaml
@@ -42,7 +42,7 @@ spec:
       value: $(body.sender.login)
     - name: "base_ref"
       value: $(body.ref)
-    - name: "head_ref" # head ref become the same as base ref
+    - name: "head_ref"
       value: $(body.ref)
     - name: "installation_id"
       value: $(body.installation.id)
diff --git a/pkg/webvcs/github/events.go b/pkg/webvcs/github/events.go
index d07dc4cb..ab9e1e88 100644
--- a/pkg/webvcs/github/events.go
+++ b/pkg/webvcs/github/events.go
@@ -5,6 +5,7 @@ import (
 	"encoding/json"
 	"errors"
 	"fmt"
+	"io/ioutil"
 	"net/http"
 	"os"
 	"path"
@@ -55,7 +56,7 @@ func (v *VCS) getAppToken() error {
 	}
 
 	// read application_id from the secret workspace
-	b, err := os.ReadFile(filepath.Join(workspacePath, "application_id"))
+	b, err := ioutil.ReadFile(filepath.Join(workspacePath, "application_id"))
 	if err != nil {
 		return err
 	}
@@ -79,10 +80,7 @@ func (v *VCS) getAppToken() error {
 			gheURL = "https://" + gheURL
 		}
 
-		v.Client, err = github.NewEnterpriseClient(gheURL, "", &http.Client{Transport: itr})
-		if err != nil {
-			return err
-		}
+		v.Client, _ = github.NewEnterpriseClient(gheURL, "", &http.Client{Transport: itr})
 		itr.BaseURL = strings.TrimSuffix(v.Client.BaseURL.String(), "/")
 	} else {
 		v.Client = github.NewClient(&http.Client{Transport: itr})
@@ -97,37 +95,39 @@ func (v *VCS) ParsePayload(ctx context.Context, run *params.Run, payload string)
 	var processedevent *info.Event
 
 	// get the app token if it exist first
-	err := v.getAppToken()
-	if err != nil {
-		return &info.Event{}, err
+	if err := v.getAppToken(); err != nil {
+		return nil, err
 	}
 
 	payloadTreated := v.payloadFix(payload)
 	event, err := github.ParseWebHook(run.Info.Event.EventType, payloadTreated)
 	if err != nil {
-		return &info.Event{}, err
+		return nil, err
 	}
 
-	err = json.Unmarshal(payloadTreated, &event)
-	if err != nil {
-		return &info.Event{}, err
-	}
+	// should not get invalid json since we already check it in github.ParseWebHook
+	_ = json.Unmarshal(payloadTreated, &event)
 
 	switch event := event.(type) {
 	case *github.CheckRunEvent:
-		if run.Info.Event.TriggerTarget == "issue-recheck" {
-			processedevent, err = v.handleReRequestEvent(ctx, run.Clients.Log, event)
-			if err != nil {
-				return &info.Event{}, err
-			}
+		if v.Client == nil {
+			return nil, fmt.Errorf("reqrequest is only supported with github apps integration")
+		}
+
+		if run.Info.Event.TriggerTarget != "issue-recheck" {
+			return nil, fmt.Errorf("only issue recheck is supported in checkrunevent")
+		}
+		processedevent, err = v.handleReRequestEvent(ctx, run.Clients.Log, event)
+		if err != nil {
+			return nil, err
 		}
 	case *github.IssueCommentEvent:
 		if v.Client == nil {
-			return &info.Event{}, fmt.Errorf("gitops style comments operation is only supported with github apps integration")
+			return nil, fmt.Errorf("gitops style comments operation is only supported with github apps integration")
 		}
 		processedevent, err = v.handleIssueCommentEvent(ctx, run.Clients.Log, event)
 		if err != nil {
-			return &info.Event{}, err
+			return nil, err
 		}
 	case *github.PushEvent:
 		processedevent = &info.Event{
@@ -158,7 +158,7 @@ func (v *VCS) ParsePayload(ctx context.Context, run *params.Run, payload string)
 		}
 
 	default:
-		return &info.Event{}, errors.New("this event is not supported")
+		return nil, errors.New("this event is not supported")
 	}
 
 	processedevent.Event = event
@@ -194,7 +194,7 @@ func (v *VCS) handleReRequestEvent(ctx context.Context, log *zap.SugaredLogger,
 func convertPullRequestURLtoNumber(pullRequest string) (int, error) {
 	prNumber, err := strconv.Atoi(path.Base(pullRequest))
 	if err != nil {
-		return -1, err
+		return -1, fmt.Errorf("bad pull request number html_url number: %w", err)
 	}
 	return prNumber, nil
 }
@@ -204,7 +204,6 @@ func (v *VCS) handleIssueCommentEvent(ctx context.Context, log *zap.SugaredLogge
 		Owner:      event.GetRepo().GetOwner().GetLogin(),
 		Repository: event.GetRepo().GetName(),
 	}
-
 	if !event.GetIssue().IsPullRequest() {
 		return &info.Event{}, fmt.Errorf("issue comment is not coming from a pull_request")
 	}
diff --git a/pkg/webvcs/github/status.go b/pkg/webvcs/github/status.go
index 085d9f86..423a2f5b 100644
--- a/pkg/webvcs/github/status.go
+++ b/pkg/webvcs/github/status.go
@@ -75,6 +75,7 @@ func (v *VCS) createCheckRunStatus(ctx context.Context, runevent *info.Event, pa
 // createStatusCommit use the classic/old statuses API which is available when we
 // don't have a github app token
 func (v *VCS) createStatusCommit(ctx context.Context, runevent *info.Event, pacopts *info.PacOpts, status webvcs.StatusOpts) error {
+	var err error
 	now := time.Now()
 	switch status.Conclusion {
 	case "skipped":
@@ -94,8 +95,7 @@ func (v *VCS) createStatusCommit(ctx context.Context, runevent *info.Event, paco
 		CreatedAt:   &now,
 	}
 
-	_, _, err := v.Client.Repositories.CreateStatus(ctx, runevent.Owner, runevent.Repository, runevent.SHA, ghstatus)
-	if err != nil {
+	if _, _, err := v.Client.Repositories.CreateStatus(ctx, runevent.Owner, runevent.Repository, runevent.SHA, ghstatus); err != nil {
 		return err
 	}
 	if status.Status == "completed" && status.Text != "" && runevent.EventType == "pull_request" {


Test patch:
diff --git a/pkg/webvcs/github/events_test.go b/pkg/webvcs/github/events_test.go
index d96babe8..818d84be 100644
--- a/pkg/webvcs/github/events_test.go
+++ b/pkg/webvcs/github/events_test.go
@@ -1,10 +1,10 @@
 package github
 
 import (
+	"encoding/json"
 	"fmt"
 	"io/ioutil"
 	"net/http"
-	"strings"
 	"testing"
 
 	"github.com/google/go-github/v39/github"
@@ -13,9 +13,63 @@ import (
 	"github.com/openshift-pipelines/pipelines-as-code/pkg/params/info"
 	ghtesthelper "github.com/openshift-pipelines/pipelines-as-code/pkg/test/github"
 	"gotest.tools/v3/assert"
+	"gotest.tools/v3/env"
+	"gotest.tools/v3/fs"
 	rtesting "knative.dev/pkg/reconciler/testing"
 )
 
+// script kiddies, don't get too excited, this has been randomly generated with random words
+const fakePrivateKey = `-----BEGIN RSA PRIVATE KEY-----
+MIICXAIBAAKBgQC6GorZBeri0eVERMZQDFh5E1RMPjFk9AevaWr27yJse6eiUlos
+gY2L2vcZKLOrdvVR+TLLapIMFfg1E1qVr1iTHP3IiSCs1uW6NKDmxEQc9Uf/fG9c
+i56tGmTVxLkC94AvlVFmgxtWfHdP3lF2O0EcfRyIi6EIbGkWDqWQVEQG2wIDAQAB
+AoGAaKOd6FK0dB5Si6Uj4ERgxosAvfHGMh4n6BAc7YUd1ONeKR2myBl77eQLRaEm
+DMXRP+sfDVL5lUQRED62ky1JXlDc0TmdLiO+2YVyXI5Tbej0Q6wGVC25/HedguUX
+fw+MdKe8jsOOXVRLrJ2GfpKZ2CmOKGTm/hyrFa10TmeoTxkCQQDa4fvqZYD4vOwZ
+CplONnVk+PyQETj+mAyUiBnHEeLpztMImNLVwZbrmMHnBtCNx5We10oCLW+Qndfw
+Xi4LgliVAkEA2amSV+TZiUVQmm5j9yzon0rt1FK+cmVWfRS/JAUXyvl+Xh/J+7Gu
+QzoEGJNAnzkUIZuwhTfNRWlzURWYA8BVrwJAZFQhfJd6PomaTwAktU0REm9ulTrP
+vSNE4PBhoHX6ZOGAqfgi7AgIfYVPm+3rupE5a82TBtx8vvUa/fqtcGkW4QJAaL9t
+WPUeJyx/XMJxQzuOe1JA4CQt2LmiBLHeRoRY7ephgQSFXKYmed3KqNT8jWOXp5DY
+Q1QWaigUQdpFfNCrqwJBANLgWaJV722PhQXOCmR+INvZ7ksIhJVcq/x1l2BYOLw2
+QsncVExbMiPa9Oclo5qLuTosS8qwHm1MJEytp3/SkB8=
+-----END RSA PRIVATE KEY-----`
+
+var sampleRepo = &github.Repository{
+	Owner: &github.User{
+		Login: github.String("owner"),
+	},
+	Name:          github.String("reponame"),
+	DefaultBranch: github.String("defaultbranch"),
+	HTMLURL:       github.String("https://github.com/owner/repo"),
+}
+
+var samplePRevent = github.PullRequestEvent{
+	PullRequest: &github.PullRequest{
+		Head: &github.PullRequestBranch{
+			SHA: github.String("sampleHeadsha"),
+			Ref: github.String("headred"),
+		},
+		Base: &github.PullRequestBranch{
+			SHA: github.String("basesha"),
+			Ref: github.String("baseref"),
+		},
+		User: &github.User{
+			Login: github.String("user"),
+		},
+	},
+	Repo: sampleRepo,
+}
+
+var samplePR = github.PullRequest{
+	Number: github.Int(54321),
+	Head: &github.PullRequestBranch{
+		SHA:  github.String("samplePRsha"),
+		Repo: sampleRepo,
+	},
+}
+
+// TODO: better testing matrix against only public function like we do for bitbucket-cloud
 func TestPayLoadFix(t *testing.T) {
 	b, err := ioutil.ReadFile("testdata/pull_request_with_newlines.json")
 	assert.NilError(t, err)
@@ -33,7 +87,7 @@ func TestPayLoadFix(t *testing.T) {
 		Client: fakeclient,
 	}
 
-	logger, _ := getLogger()
+	logger := getLogger()
 
 	event := &info.Event{
 		EventType:     "pull_request",
@@ -55,299 +109,360 @@ func TestPayLoadFix(t *testing.T) {
 	assert.NilError(t, err)
 }
 
-func TestParsePayloadRerequestFromPullRequest(t *testing.T) {
-	checkrunSender := "jean-pierre"
-	prOwner := "owner"
-	repoName := "repo"
-	prNumber := "123"
-	sha := "ParsePayloadRerequestFromPullRequestSHA"
-	checkrunEvent := fmt.Sprintf(`{"action": "rerequested",
-	"sender": {"login": "%s"},
-	"check_run": {"check_suite": {"pull_requests": [{"number": %s}]}},
-	"repository": {"name": "%s", "owner": {"login": "%s"}}}`,
-		checkrunSender, prNumber, repoName, prOwner)
+func TestParsePayLoad(t *testing.T) {
 	fakeclient, mux, _, teardown := ghtesthelper.SetupGH()
 	defer teardown()
-	mux.HandleFunc("/repos/"+prOwner+"/"+repoName+"/pulls/"+prNumber, func(rw http.ResponseWriter, r *http.Request) {
-		_, _ = fmt.Fprintf(rw, `{"head": {"sha": "%s", "ref": "123"}, "user": {"login": "%s"}}`, sha, prOwner)
-	})
-	mux.HandleFunc("/repos/owner/repo/commits/"+sha, func(w http.ResponseWriter, r *http.Request) {
-		_, _ = fmt.Fprint(w, `{"commit": {"message": "HELLO"}}`)
-	})
-	mux.HandleFunc("/repos/owner/repo/git/commits/"+sha, func(w http.ResponseWriter, r *http.Request) {
-		_, _ = fmt.Fprint(w, `{"commit": {"message": "HELLO"}}`)
-	})
-	ctx, _ := rtesting.SetupFakeContext(t)
-	gvcs := VCS{
-		Client: fakeclient,
-	}
-	logger, observer := getLogger()
-	event := &info.Event{
-		EventType:     "check_run",
-		TriggerTarget: "issue-recheck",
-	}
-	run := &params.Run{
-		Clients: clients.Clients{
-			Log: logger,
+
+	tests := []struct {
+		name               string
+		wantErrString      string
+		eventType          string
+		payloadEventStruct interface{}
+		jeez               string
+		triggerTarget      string
+		githubClient       *github.Client
+		muxReplies         map[string]interface{}
+		shaRet             string
+	}{
+		{
+			name:          "bad/unknow event",
+			wantErrString: "unknown X-Github-Event",
+			eventType:     "unknown",
 		},
-		Info: info.Info{
-			Event: event,
+		{
+			name:          "bad/invalid json",
+			wantErrString: "invalid character",
+			eventType:     "pull_request",
+			jeez:          "xxxx",
 		},
-	}
-	runinfo, err := gvcs.ParsePayload(ctx, run, checkrunEvent)
-	assert.NilError(t, err)
-
-	assert.Equal(t, prOwner, runinfo.Owner)
-	assert.Equal(t, repoName, runinfo.Repository)
-	assert.Assert(t, checkrunSender != runinfo.Sender)
-	assert.Equal(t, runinfo.EventType, "pull_request")
-	assert.Assert(t, strings.Contains(observer.TakeAll()[0].Message, "Recheck of PR"))
-}
-
-func TestParsePayloadRerequestFromPush(t *testing.T) {
-	sender := "jean-pierre"
-	headBranch := "tartonpion"
-	headSHA := "TestParsePayloadRerequestFromPushSHA"
-	owner := "owner"
-	repository := "repo"
-	url := fmt.Sprintf("https://github.com/%s/%s", owner, repository)
-	checkrunEvent := fmt.Sprintf(`{
-  "action": "rerequested",
-  "check_run": {
-    "check_suite": {
-      "head_branch": "%s",
-      "head_sha": "%s",
-      "pull_requests": []
-    }
-  },
-  "repository": {
-    "default_branch": "main",
-    "html_url": "%s",
-    "name": "%s",
-    "owner": {
-      "login": "%s"
-    }
-  },
-  "sender": {
-    "login": "%s"
-  }
-}`,
-		headBranch, headSHA, url, repository, owner, sender)
-	ctx, _ := rtesting.SetupFakeContext(t)
-	fakeclient, mux, _, teardown := ghtesthelper.SetupGH()
-	defer teardown()
-	gvcs := VCS{
-		Client: fakeclient,
-	}
-	mux.HandleFunc("/repos/owner/repo/commits/"+headSHA, func(w http.ResponseWriter, r *http.Request) {
-		_, _ = fmt.Fprint(w, `{"commit": {"message": "HELLO"}}`)
-	})
-	mux.HandleFunc("/repos/owner/repo/git/commits/"+headSHA, func(w http.ResponseWriter, r *http.Request) {
-		_, _ = fmt.Fprint(w, `{"commit": {"message": "HELLO"}}`)
-	})
-
-	event := &info.Event{
-		EventType:     "check_run",
-		TriggerTarget: "issue-recheck",
-	}
-	logger, _ := getLogger()
-
-	run := &params.Run{
-		Clients: clients.Clients{
-			Log: logger,
+		{
+			name:               "bad/not supported",
+			wantErrString:      "this event is not supported",
+			eventType:          "pull_request_review_comment",
+			payloadEventStruct: github.PullRequestReviewCommentEvent{Action: github.String("created")},
 		},
-		Info: info.Info{
-			Event: event,
+		{
+			name:               "bad/check run only issue recheck supported",
+			wantErrString:      "only issue recheck is supported",
+			eventType:          "check_run",
+			triggerTarget:      "nonopetitrobot",
+			payloadEventStruct: github.CheckRunEvent{Action: github.String("created")},
+			githubClient:       fakeclient,
+		},
+		{
+			name:               "bad/check run only with github apps",
+			wantErrString:      "only supported with github apps",
+			eventType:          "check_run",
+			payloadEventStruct: github.CheckRunEvent{Action: github.String("created")},
+		},
+		{
+			name:               "bad/issue comment retest only with github apps",
+			wantErrString:      "only supported with github apps",
+			eventType:          "issue_comment",
+			payloadEventStruct: github.IssueCommentEvent{Action: github.String("created")},
+		},
+		{
+			name:               "bad/issue comment not coming from pull request",
+			eventType:          "issue_comment",
+			githubClient:       fakeclient,
+			payloadEventStruct: github.IssueCommentEvent{Issue: &github.Issue{}},
+			wantErrString:      "issue comment is not coming from a pull_request",
+		},
+		{
+			name:         "bad/issue comment invalid pullrequest",
+			eventType:    "issue_comment",
+			githubClient: fakeclient,
+			payloadEventStruct: github.IssueCommentEvent{Issue: &github.Issue{
+				PullRequestLinks: &github.PullRequestLinks{
+					HTMLURL: github.String("/bad"),
+				},
+			}},
+			wantErrString: "bad pull request number",
+		},
+		{
+			name:          "bad/rerequest error fetching PR",
+			githubClient:  fakeclient,
+			eventType:     "check_run",
+			triggerTarget: "issue-recheck",
+			wantErrString: "404",
+			payloadEventStruct: github.CheckRunEvent{
+				Repo: sampleRepo,
+				CheckRun: &github.CheckRun{
+					CheckSuite: &github.CheckSuite{
+						PullRequests: []*github.PullRequest{&samplePR},
+					},
+				},
+			},
+			shaRet: "samplePRsha",
 		},
-	}
-	runinfo, err := gvcs.ParsePayload(ctx, run, checkrunEvent)
-	assert.NilError(t, err)
-
-	assert.Equal(t, runinfo.EventType, "push")
-	assert.Equal(t, runinfo.HeadBranch, headBranch)
-	assert.Equal(t, runinfo.Owner, owner)
-	assert.Equal(t, runinfo.Repository, repository)
-	assert.Equal(t, runinfo.URL, url)
-	assert.Assert(t, sender == runinfo.Sender) // TODO: should it be set to the push sender?
-}
-
-func TestParsePayLoadRetest(t *testing.T) {
-	issueSender := "tartanpion"
-	prOwner := "user1"
-	repoOwner := "openshift"
-	repoName := "pipelines"
-	prNumber := "123"
-	sha := "TestParsePayLoadRetestSHA"
-
-	fakeclient, mux, _, teardown := ghtesthelper.SetupGH()
-	defer teardown()
-	mux.HandleFunc("/repos/"+prOwner+"/"+repoName+"/pulls/"+prNumber, func(rw http.ResponseWriter, r *http.Request) {
-		_, _ = fmt.Fprintf(rw, `{"head": {"sha": "%s", "ref": "123"}, "user": {"login": "%s"}}`, sha, prOwner)
-	})
-	mux.HandleFunc("/repos/user1/pipelines/commits/"+sha, func(w http.ResponseWriter, r *http.Request) {
-		_, _ = fmt.Fprint(w, `{"commit": {"message": "HELLO"}}`)
-	})
-	mux.HandleFunc("/repos/user1/pipelines/git/commits/"+sha, func(w http.ResponseWriter, r *http.Request) {
-		_, _ = fmt.Fprint(w, `{"commit": {"message": "HELLO"}}`)
-	})
-	issueEvent := fmt.Sprintf(`{
-  "sender": {
-	"login": "%s"
-  },
-  "repository": {
-	"name": "%s",
-	"owner": {
-	  "login": "%s"
-	}
-  },
-  "issue": {
-	"pull_request": {
-	  "html_url": "https://github.com/%s/%s/pull/%s"
-	}
-  }
-}`, issueSender, repoName, prOwner, repoName, repoOwner, prNumber)
 
-	ctx, _ := rtesting.SetupFakeContext(t)
-	logger, observer := getLogger()
-	gvcs := VCS{
-		Client: fakeclient,
-	}
-	// TODO
-	event := &info.Event{
-		EventType:     "issue_comment",
-		TriggerTarget: "issue_comment",
-	}
-	run := &params.Run{
-		Clients: clients.Clients{
-			Log: logger,
+		{
+			name:          "good/rerequest on pull request",
+			eventType:     "check_run",
+			githubClient:  fakeclient,
+			triggerTarget: "issue-recheck",
+			payloadEventStruct: github.CheckRunEvent{
+				Repo: sampleRepo,
+				CheckRun: &github.CheckRun{
+					CheckSuite: &github.CheckSuite{
+						PullRequests: []*github.PullRequest{&samplePR},
+					},
+				},
+			},
+			muxReplies: map[string]interface{}{"/repos/owner/reponame/pulls/54321": samplePR},
+			shaRet:     "samplePRsha",
 		},
-		Info: info.Info{
-			Event: event,
-			Pac: &info.PacOpts{
-				VCSToken: "TOKENSET",
+		{
+			name:          "good/rerequest on push",
+			eventType:     "check_run",
+			githubClient:  fakeclient,
+			triggerTarget: "issue-recheck",
+			payloadEventStruct: github.CheckRunEvent{
+				Repo: sampleRepo,
+				CheckRun: &github.CheckRun{
+					CheckSuite: &github.CheckSuite{
+						HeadSHA: github.String("headSHACheckSuite"),
+					},
+				},
+			},
+			shaRet: "headSHACheckSuite",
+		},
+		{
+			name:         "good/issue comment",
+			eventType:    "issue_comment",
+			githubClient: fakeclient,
+			payloadEventStruct: github.IssueCommentEvent{
+				Issue: &github.Issue{
+					PullRequestLinks: &github.PullRequestLinks{
+						HTMLURL: github.String("/666"),
+					},
+				},
+				Repo: sampleRepo,
+			},
+			muxReplies: map[string]interface{}{"/repos/owner/reponame/pulls/666": samplePR},
+			shaRet:     "samplePRsha",
+		},
+		{
+			name:               "good/pull request",
+			eventType:          "pull_request",
+			triggerTarget:      "pull_request",
+			payloadEventStruct: samplePRevent,
+			shaRet:             "sampleHeadsha",
+		},
+		{
+			name:          "good/push",
+			eventType:     "push",
+			triggerTarget: "push",
+			payloadEventStruct: github.PushEvent{
+				Repo: &github.PushEventRepository{
+					Owner: &github.User{Login: github.String("owner")},
+					Name:  github.String("pushRepo"),
+				},
+				HeadCommit: &github.HeadCommit{ID: github.String("SHAPush")},
 			},
+			shaRet: "SHAPush",
 		},
 	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx, _ := rtesting.SetupFakeContext(t)
 
-	runinfo, err := gvcs.ParsePayload(ctx, run, issueEvent)
-	assert.NilError(t, err)
-	assert.Equal(t, prOwner, runinfo.Owner)
-	// Make sure the PR owner is the runinfo.Owner and not the issueSender
-	assert.Assert(t, issueSender != runinfo.Owner)
-	firstObservedMessage := observer.TakeAll()[0].Message
-	assert.Assert(t, strings.Contains(firstObservedMessage, "recheck"))
-	assert.Equal(t, runinfo.EventType, "pull_request")
-
-	// We cannot parse payload without a token when getting from issue_comment
-	gvcs.Client = nil
-	runinfo, err = gvcs.ParsePayload(ctx, run, issueEvent)
-	assert.ErrorContains(t, err, "gitops style comments operation is only supported with github apps")
-	assert.Assert(t, runinfo.Event == nil)
-}
+			for key, value := range tt.muxReplies {
+				mux.HandleFunc(key, func(rw http.ResponseWriter, r *http.Request) {
+					bjeez, _ := json.Marshal(value)
+					fmt.Fprint(rw, string(bjeez))
+				})
+			}
+			gvcs := VCS{
+				Client: tt.githubClient,
+			}
+			logger := getLogger()
+			event := &info.Event{
+				EventType:     tt.eventType,
+				TriggerTarget: tt.triggerTarget,
+			}
 
-func TestParsePayload(t *testing.T) {
-	b, err := ioutil.ReadFile("testdata/pull_request.json")
-	assert.NilError(t, err)
-	fakeclient, mux, _, teardown := ghtesthelper.SetupGH()
-	defer teardown()
-	mux.HandleFunc("/repos/chmouel/scratchpad/commits/cc8334de8e056317d18bd00c2588c3f7c95af294", func(w http.ResponseWriter, r *http.Request) {
-		_, _ = fmt.Fprint(w, `{"commit": {"message": "HELLO"}}`)
-	})
-	mux.HandleFunc("/repos/chmouel/scratchpad/git/commits/cc8334de8e056317d18bd00c2588c3f7c95af294", func(w http.ResponseWriter, r *http.Request) {
-		_, _ = fmt.Fprint(w, `{"commit": {"message": "HELLO"}}`)
-	})
-	gvcs := VCS{
-		Client: fakeclient,
+			run := &params.Run{
+				Clients: clients.Clients{
+					Log: logger,
+				},
+				Info: info.Info{
+					Event: event,
+				},
+			}
+			bjeez, _ := json.Marshal(tt.payloadEventStruct)
+			jeez := string(bjeez)
+			if tt.jeez != "" {
+				jeez = tt.jeez
+			}
+			ret, err := gvcs.ParsePayload(ctx, run, jeez)
+			if tt.wantErrString != "" {
+				assert.ErrorContains(t, err, tt.wantErrString)
+				return
+			}
+			assert.NilError(t, err)
+			assert.Assert(t, ret != nil)
+			assert.Equal(t, tt.shaRet, ret.SHA)
+		})
 	}
-	ctx, _ := rtesting.SetupFakeContext(t)
-	logger, _ := getLogger()
+}
 
-	event := &info.Event{
-		EventType:     "pull_request",
-		TriggerTarget: "pull_request",
-	}
-	run := &params.Run{
-		Clients: clients.Clients{
-			Log: logger,
+func TestAppTokenGeneration(t *testing.T) {
+	tests := []struct {
+		name          string
+		wantErr       bool
+		nilClient     bool
+		envs          map[string]string
+		wsSecretFiles map[string]string
+		resultBaseURL string
+	}{
+		{
+			name: "Env not set",
+			envs: map[string]string{
+				"FOO": "bar",
+			},
+			nilClient: true,
 		},
-		Info: info.Info{
-			Event: event,
+		{
+			name: "Bad Account ID",
+			envs: map[string]string{
+				"PAC_INSTALLATION_ID":  "bad",
+				"PAC_WORKSPACE_SECRET": "xxx",
+			},
+			wantErr: true,
 		},
-	}
-	runinfo, err := gvcs.ParsePayload(ctx, run, string(b))
-	assert.NilError(t, err)
-	assert.Assert(t, runinfo.BaseBranch == "master")
-	assert.Assert(t, runinfo.Owner == "chmouel")
-	assert.Assert(t, runinfo.Repository == "scratchpad")
-	assert.Equal(t, runinfo.EventType, "pull_request")
-	assert.Assert(t, runinfo.URL == "https://github.com/chmouel/scratchpad")
-}
-
-func TestParsePayloadInvalid(t *testing.T) {
-	ctx, _ := rtesting.SetupFakeContext(t)
-	gvcs := VCS{
-		Token:  github.String("none"),
-		APIURL: github.String("nothing"),
-	}
-	logger, _ := getLogger()
-	event := &info.Event{
-		EventType:     "pull_request",
-		TriggerTarget: "pull_request",
-	}
-	run := &params.Run{
-		Clients: clients.Clients{
-			Log: logger,
+		{
+			name: "bad/Workspace path doesn't exist",
+			envs: map[string]string{
+				"PAC_INSTALLATION_ID":  "11111",
+				"PAC_WORKSPACE_SECRET": "not/here",
+			},
+			wantErr: true,
 		},
-		Info: info.Info{
-			Event: event,
+		{
+			name: "bad/Application ID in workspace doesn't exist",
+			envs: map[string]string{
+				"PAC_INSTALLATION_ID":  "11111",
+				"PAC_WORKSPACE_SECRET": "here",
+			},
+			wsSecretFiles: map[string]string{
+				"noapplication_id": "Foo",
+			},
+			wantErr: true,
 		},
-	}
-	_, err := gvcs.ParsePayload(ctx, run, "hello moto")
-	assert.ErrorContains(t, err, "invalid character")
-}
-
-func TestParsePayloadUnkownEvent(t *testing.T) {
-	ctx, _ := rtesting.SetupFakeContext(t)
-	gvcs := VCS{
-		Token:  github.String("none"),
-		APIURL: github.String(""),
-	}
-	logger, _ := getLogger()
-	event := &info.Event{
-		EventType:     "foo",
-		TriggerTarget: "foo",
-	}
-	run := &params.Run{
-		Clients: clients.Clients{
-			Log: logger,
+		{
+			name: "bad/wrong ApplicationID",
+			envs: map[string]string{
+				"PAC_INSTALLATION_ID":  "11111",
+				"PAC_WORKSPACE_SECRET": "here",
+			},
+			wsSecretFiles: map[string]string{
+				"application_id": "BAD",
+			},
+			wantErr: true,
 		},
-		Info: info.Info{
-			Event: event,
+		{
+			name: "bad/Private Key not present",
+			envs: map[string]string{
+				"PAC_INSTALLATION_ID":  "11111",
+				"PAC_WORKSPACE_SECRET": "here",
+			},
+			wsSecretFiles: map[string]string{
+				"application_id": "2222",
+			},
+			wantErr: true,
 		},
-	}
-	_, err := gvcs.ParsePayload(ctx, run, "{\"hello\": \"moto\"}")
-	assert.ErrorContains(t, err, "unknown X-Github-Event")
-}
-
-func TestParsePayCannotParse(t *testing.T) {
-	ctx, _ := rtesting.SetupFakeContext(t)
-	gvcs := VCS{
-		Token:  github.String("none"),
-		APIURL: github.String(""),
-	}
-	logger, _ := getLogger()
-	event := &info.Event{
-		EventType:     "gollum",
-		TriggerTarget: "gollum",
-	}
-	run := &params.Run{
-		Clients: clients.Clients{
-			Log: logger,
+		{
+			name: "Bad/Private Key chelou",
+			envs: map[string]string{
+				"PAC_INSTALLATION_ID":  "11111",
+				"PAC_WORKSPACE_SECRET": "here",
+				"PAC_WEBVCS_APIURL":    "foo.bar.com",
+			},
+			wsSecretFiles: map[string]string{
+				"application_id": "2222",
+				"private.key":    "hello",
+			},
+			wantErr: true,
 		},
-		Info: info.Info{
-			Event: event,
+		{
+			name: "Good/ghe base domain",
+			envs: map[string]string{
+				"PAC_INSTALLATION_ID":  "11111",
+				"PAC_WORKSPACE_SECRET": "here",
+				"PAC_WEBVCS_APIURL":    "foo.bar.com",
+			},
+			wsSecretFiles: map[string]string{
+				"application_id": "2222",
+				"private.key":    fakePrivateKey,
+			},
+			resultBaseURL: "https://foo.bar.com/api/v3/",
+		},
+		{
+			name: "Good/full ghe url",
+			envs: map[string]string{
+				"PAC_INSTALLATION_ID":  "11111",
+				"PAC_WORKSPACE_SECRET": "here",
+				"PAC_WEBVCS_APIURL":    "https://alpha.beta.com",
+			},
+			wsSecretFiles: map[string]string{
+				"application_id": "2222",
+				"private.key":    fakePrivateKey,
+			},
+			resultBaseURL: "https://alpha.beta.com/api/v3/",
 		},
+		{
+			name: "Good/default github url",
+			envs: map[string]string{
+				"PAC_INSTALLATION_ID":  "11111",
+				"PAC_WORKSPACE_SECRET": "here",
+			},
+			wsSecretFiles: map[string]string{
+				"application_id": "2222",
+				"private.key":    fakePrivateKey,
+			},
+			resultBaseURL: "https://api.github.com/",
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if s, ok := tt.envs["PAC_WORKSPACE_SECRET"]; ok && s == "here" {
+				d := fs.NewDir(t, "workspace-secret", fs.WithFiles(tt.wsSecretFiles))
+				defer d.Remove()
+				tt.envs["PAC_WORKSPACE_SECRET"] = d.Path()
+			}
+			envRemove := env.PatchAll(t, tt.envs)
+			defer envRemove()
+
+			ctx, _ := rtesting.SetupFakeContext(t)
+			jeez, _ := json.Marshal(samplePRevent)
+			gvcs := VCS{}
+			logger := getLogger()
+			event := &info.Event{
+				EventType:     "pull_request",
+				TriggerTarget: "pull_request",
+			}
+			run := &params.Run{
+				Clients: clients.Clients{
+					Log: logger,
+				},
+				Info: info.Info{
+					Event: event,
+				},
+			}
+
+			_, err := gvcs.ParsePayload(ctx, run, string(jeez))
+			if tt.wantErr {
+				assert.Assert(t, err != nil)
+				return
+			}
+			assert.NilError(t, err)
+			if tt.nilClient {
+				assert.Assert(t, gvcs.Client == nil)
+				return
+			}
+			assert.Assert(t, gvcs.Client != nil)
+			assert.Equal(t, gvcs.Client.BaseURL.String(), tt.resultBaseURL)
+		})
 	}
-	_, err := gvcs.ParsePayload(ctx, run, "{}")
-	assert.Error(t, err, "this event is not supported")
 }
diff --git a/pkg/webvcs/github/github_test.go b/pkg/webvcs/github/github_test.go
index 46ef911c..8fc119e1 100644
--- a/pkg/webvcs/github/github_test.go
+++ b/pkg/webvcs/github/github_test.go
@@ -16,10 +16,10 @@ import (
 	"gotest.tools/v3/assert"
 )
 
-func getLogger() (*zap.SugaredLogger, *zapobserver.ObservedLogs) {
-	observer, logobserver := zapobserver.New(zap.InfoLevel)
+func getLogger() *zap.SugaredLogger {
+	observer, _ := zapobserver.New(zap.InfoLevel)
 	logger := zap.New(observer).Sugar()
-	return logger, logobserver
+	return logger
 }
 
 func setupFakesURLS() (client VCS, teardown func()) {
diff --git a/test/testdata/pipeline_remote_annotations.yaml b/test/testdata/pipeline_remote_annotations.yaml
index a535a6bc..ba28cb3e 100644
--- a/test/testdata/pipeline_remote_annotations.yaml
+++ b/test/testdata/pipeline_remote_annotations.yaml
@@ -27,18 +27,3 @@ spec:
     - name: task-referenced-internally
       taskRef:
         name: task-referenced-internally
-
-    # - name: git-clone-from-catalog
-    #   taskRef:
-    #     name: git-clone
-    #   params:
-    #     - name: url
-    #       value: $(params.repo_url)
-    #     - name: revision
-          # value: $(params.revision)
-
-      # workspaces:
-      #   - name: output
-      #     workspace: source
-      #   - name: basic-auth
-          # workspace: basic-auth
diff --git a/test/testdata/pipelinerun_remote_annotations.yaml b/test/testdata/pipelinerun_remote_annotations.yaml
index 1ae50004..3f9b2a8f 100644
--- a/test/testdata/pipelinerun_remote_annotations.yaml
+++ b/test/testdata/pipelinerun_remote_annotations.yaml
@@ -12,17 +12,3 @@ metadata:
 spec:
   pipelineRef:
     name: pipeline-remote-annotations
-  # params:
-  #   - name: repo_url
-  #     value: "{{repo_url}}"
-  #   - name: revision
-  #     value: "{{revision}}"
-  # workspaces:
-  # - name: source
-  #   volumeClaimTemplate:
-  #     spec:
-  #       accessModes:
-  #         - ReadWriteOnce
-  #       resources:
-  #         requests:
-  #           storage: 1Gi