|
| 1 | +package gitkit_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/sosedoff/gitkit" |
| 7 | + "github.com/stretchr/testify/assert" |
| 8 | +) |
| 9 | + |
| 10 | +type gitReceiveMock struct { |
| 11 | + name string |
| 12 | + masterOnly bool |
| 13 | + allowedBranches []string |
| 14 | + ref string |
| 15 | + isErr bool |
| 16 | +} |
| 17 | + |
| 18 | +func TestMasterOnly(t *testing.T) { |
| 19 | + testCases := []gitReceiveMock{ |
| 20 | + { |
| 21 | + name: "push to master, no error", |
| 22 | + masterOnly: true, |
| 23 | + ref: "refs/heads/master", |
| 24 | + isErr: false, |
| 25 | + }, |
| 26 | + { |
| 27 | + name: "push to a branch, should trigger error", |
| 28 | + masterOnly: true, |
| 29 | + ref: "refs/heads/branch", |
| 30 | + isErr: true, |
| 31 | + }, |
| 32 | + } |
| 33 | + |
| 34 | + for _, tc := range testCases { |
| 35 | + r := &gitkit.Receiver{ |
| 36 | + MasterOnly: tc.masterOnly, |
| 37 | + } |
| 38 | + |
| 39 | + err := r.CheckAllowedBranch(&gitkit.HookInfo{ |
| 40 | + Ref: tc.ref, |
| 41 | + }) |
| 42 | + |
| 43 | + if !tc.isErr { |
| 44 | + assert.NoError(t, err, "expected no error: %s", tc.name) |
| 45 | + } else { |
| 46 | + assert.Error(t, err, "expected an error: %s", tc.name) |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +func TestAllowedBranches(t *testing.T) { |
| 52 | + testCases := []gitReceiveMock{ |
| 53 | + { |
| 54 | + name: "push to master, no error", |
| 55 | + allowedBranches: []string{"refs/heads/master"}, |
| 56 | + ref: "refs/heads/master", |
| 57 | + isErr: false, |
| 58 | + }, |
| 59 | + { |
| 60 | + name: "push to a branch, should trigger error", |
| 61 | + allowedBranches: []string{"refs/heads/master"}, |
| 62 | + ref: "refs/heads/some-branch", |
| 63 | + isErr: true, |
| 64 | + }, |
| 65 | + { |
| 66 | + name: "push to another-branch", |
| 67 | + allowedBranches: []string{"refs/heads/another-branch"}, |
| 68 | + ref: "refs/heads/another-branch", |
| 69 | + isErr: false, |
| 70 | + }, |
| 71 | + { |
| 72 | + name: "push to main and only allow main", |
| 73 | + allowedBranches: []string{"refs/heads/main"}, |
| 74 | + ref: "refs/heads/main", |
| 75 | + isErr: false, |
| 76 | + }, |
| 77 | + } |
| 78 | + |
| 79 | + for _, tc := range testCases { |
| 80 | + r := &gitkit.Receiver{ |
| 81 | + AllowedBranches: tc.allowedBranches, |
| 82 | + } |
| 83 | + |
| 84 | + err := r.CheckAllowedBranch(&gitkit.HookInfo{ |
| 85 | + Ref: tc.ref, |
| 86 | + }) |
| 87 | + |
| 88 | + if !tc.isErr { |
| 89 | + assert.NoError(t, err, "expected no error: %s", tc.name) |
| 90 | + } else { |
| 91 | + assert.Error(t, err, "expected an error: %s", tc.name) |
| 92 | + } |
| 93 | + } |
| 94 | +} |
0 commit comments