github.com/google/go-github/v42@v42.0.0/github/repos_environments_test.go (about)

     1  // Copyright 2021 The go-github AUTHORS. All rights reserved.
     2  //
     3  // Use of this source code is governed by a BSD-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package github
     7  
     8  import (
     9  	"context"
    10  	"encoding/json"
    11  	"fmt"
    12  	"net/http"
    13  	"testing"
    14  
    15  	"github.com/google/go-cmp/cmp"
    16  )
    17  
    18  func TestRequiredReviewer_UnmarshalJSON(t *testing.T) {
    19  	var testCases = map[string]struct {
    20  		data      []byte
    21  		wantRule  []*RequiredReviewer
    22  		wantError bool
    23  	}{
    24  		"User Reviewer": {
    25  			data:      []byte(`[{"type": "User", "reviewer": {"id": 1,"login": "octocat"}}]`),
    26  			wantRule:  []*RequiredReviewer{{Type: String("User"), Reviewer: &User{ID: Int64(1), Login: String("octocat")}}},
    27  			wantError: false,
    28  		},
    29  		"Team Reviewer": {
    30  			data:      []byte(`[{"type": "Team", "reviewer": {"id": 1, "name": "Justice League"}}]`),
    31  			wantRule:  []*RequiredReviewer{{Type: String("Team"), Reviewer: &Team{ID: Int64(1), Name: String("Justice League")}}},
    32  			wantError: false,
    33  		},
    34  		"Both Types Reviewer": {
    35  			data:      []byte(`[{"type": "User", "reviewer": {"id": 1,"login": "octocat"}},{"type": "Team", "reviewer": {"id": 1, "name": "Justice League"}}]`),
    36  			wantRule:  []*RequiredReviewer{{Type: String("User"), Reviewer: &User{ID: Int64(1), Login: String("octocat")}}, {Type: String("Team"), Reviewer: &Team{ID: Int64(1), Name: String("Justice League")}}},
    37  			wantError: false,
    38  		},
    39  		"Empty JSON Object": {
    40  			data:      []byte(`[]`),
    41  			wantRule:  []*RequiredReviewer{},
    42  			wantError: false,
    43  		},
    44  		"Bad JSON Object": {
    45  			data:      []byte(`[badjson: 1]`),
    46  			wantRule:  []*RequiredReviewer{},
    47  			wantError: true,
    48  		},
    49  		"Wrong Type Type in Reviewer Object": {
    50  			data:      []byte(`[{"type": 1, "reviewer": {"id": 1}}]`),
    51  			wantRule:  []*RequiredReviewer{{Type: nil, Reviewer: nil}},
    52  			wantError: true,
    53  		},
    54  		"Wrong ID Type in User Object": {
    55  			data:      []byte(`[{"type": "User", "reviewer": {"id": "string"}}]`),
    56  			wantRule:  []*RequiredReviewer{{Type: String("User"), Reviewer: nil}},
    57  			wantError: true,
    58  		},
    59  		"Wrong ID Type in Team Object": {
    60  			data:      []byte(`[{"type": "Team", "reviewer": {"id": "string"}}]`),
    61  			wantRule:  []*RequiredReviewer{{Type: String("Team"), Reviewer: nil}},
    62  			wantError: true,
    63  		},
    64  		"Wrong Type of Reviewer": {
    65  			data:      []byte(`[{"type": "Cat", "reviewer": {"id": 1,"login": "octocat"}}]`),
    66  			wantRule:  []*RequiredReviewer{{Type: nil, Reviewer: nil}},
    67  			wantError: true,
    68  		},
    69  	}
    70  
    71  	for name, test := range testCases {
    72  		t.Run(name, func(t *testing.T) {
    73  			rule := []*RequiredReviewer{}
    74  			err := json.Unmarshal(test.data, &rule)
    75  			if err != nil && !test.wantError {
    76  				t.Errorf("RequiredReviewer.UnmarshalJSON returned an error when we expected nil")
    77  			}
    78  			if err == nil && test.wantError {
    79  				t.Errorf("RequiredReviewer.UnmarshalJSON returned no error when we expected one")
    80  			}
    81  			if !cmp.Equal(test.wantRule, rule) {
    82  				t.Errorf("RequiredReviewer.UnmarshalJSON expected rule %+v, got %+v", test.wantRule, rule)
    83  			}
    84  		})
    85  	}
    86  }
    87  
    88  func TestCreateUpdateEnvironment_MarshalJSON(t *testing.T) {
    89  	cu := &CreateUpdateEnvironment{}
    90  
    91  	got, err := cu.MarshalJSON()
    92  	if err != nil {
    93  		t.Errorf("MarshalJSON: %v", err)
    94  	}
    95  
    96  	want := `{"wait_timer":0,"reviewers":null,"deployment_branch_policy":null}`
    97  	if string(got) != want {
    98  		t.Errorf("MarshalJSON = %s, want %v", got, want)
    99  	}
   100  }
   101  
   102  func TestRepositoriesService_ListEnvironments(t *testing.T) {
   103  	client, mux, _, teardown := setup()
   104  	defer teardown()
   105  
   106  	mux.HandleFunc("/repos/o/r/environments", func(w http.ResponseWriter, r *http.Request) {
   107  		testMethod(t, r, "GET")
   108  		fmt.Fprint(w, `{"total_count":1, "environments":[{"id":1}, {"id": 2}]}`)
   109  	})
   110  
   111  	ctx := context.Background()
   112  	environments, _, err := client.Repositories.ListEnvironments(ctx, "o", "r")
   113  	if err != nil {
   114  		t.Errorf("Repositories.ListEnvironments returned error: %v", err)
   115  	}
   116  	want := &EnvResponse{TotalCount: Int(1), Environments: []*Environment{{ID: Int64(1)}, {ID: Int64(2)}}}
   117  	if !cmp.Equal(environments, want) {
   118  		t.Errorf("Repositories.ListEnvironments returned %+v, want %+v", environments, want)
   119  	}
   120  
   121  	const methodName = "ListEnvironments"
   122  	testBadOptions(t, methodName, func() (err error) {
   123  		_, _, err = client.Repositories.ListEnvironments(ctx, "\n", "\n")
   124  		return err
   125  	})
   126  
   127  	testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {
   128  		got, resp, err := client.Repositories.ListEnvironments(ctx, "o", "r")
   129  		if got != nil {
   130  			t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got)
   131  		}
   132  		return resp, err
   133  	})
   134  }
   135  
   136  func TestRepositoriesService_GetEnvironment(t *testing.T) {
   137  	client, mux, _, teardown := setup()
   138  	defer teardown()
   139  
   140  	mux.HandleFunc("/repos/o/r/environments/e", func(w http.ResponseWriter, r *http.Request) {
   141  		testMethod(t, r, "GET")
   142  		fmt.Fprint(w, `{"id": 1,"name": "staging", "deployment_branch_policy": {"protected_branches": true,	"custom_branch_policies": false}}`)
   143  	})
   144  
   145  	ctx := context.Background()
   146  	release, resp, err := client.Repositories.GetEnvironment(ctx, "o", "r", "e")
   147  	if err != nil {
   148  		t.Errorf("Repositories.GetEnvironment returned error: %v\n%v", err, resp.Body)
   149  	}
   150  
   151  	want := &Environment{ID: Int64(1), Name: String("staging"), DeploymentBranchPolicy: &BranchPolicy{ProtectedBranches: Bool(true), CustomBranchPolicies: Bool(false)}}
   152  	if !cmp.Equal(release, want) {
   153  		t.Errorf("Repositories.GetEnvironment returned %+v, want %+v", release, want)
   154  	}
   155  
   156  	const methodName = "GetEnvironment"
   157  	testBadOptions(t, methodName, func() (err error) {
   158  		_, _, err = client.Repositories.GetEnvironment(ctx, "\n", "\n", "\n")
   159  		return err
   160  	})
   161  
   162  	testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {
   163  		got, resp, err := client.Repositories.GetEnvironment(ctx, "o", "r", "e")
   164  		if got != nil {
   165  			t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got)
   166  		}
   167  		return resp, err
   168  	})
   169  }
   170  
   171  func TestRepositoriesService_CreateEnvironment(t *testing.T) {
   172  	client, mux, _, teardown := setup()
   173  	defer teardown()
   174  
   175  	input := &CreateUpdateEnvironment{
   176  		WaitTimer: Int(30),
   177  	}
   178  
   179  	mux.HandleFunc("/repos/o/r/environments/e", func(w http.ResponseWriter, r *http.Request) {
   180  		v := new(CreateUpdateEnvironment)
   181  		json.NewDecoder(r.Body).Decode(v)
   182  
   183  		testMethod(t, r, "PUT")
   184  		want := &CreateUpdateEnvironment{WaitTimer: Int(30)}
   185  		if !cmp.Equal(v, want) {
   186  			t.Errorf("Request body = %+v, want %+v", v, want)
   187  		}
   188  		fmt.Fprint(w, `{"id": 1, "name": "staging",	"protection_rules": [{"id": 1, "type": "wait_timer", "wait_timer": 30}]}`)
   189  	})
   190  
   191  	ctx := context.Background()
   192  	release, _, err := client.Repositories.CreateUpdateEnvironment(ctx, "o", "r", "e", input)
   193  	if err != nil {
   194  		t.Errorf("Repositories.CreateUpdateEnvironment returned error: %v", err)
   195  	}
   196  
   197  	want := &Environment{ID: Int64(1), Name: String("staging"), ProtectionRules: []*ProtectionRule{{ID: Int64(1), Type: String("wait_timer"), WaitTimer: Int(30)}}}
   198  	if !cmp.Equal(release, want) {
   199  		t.Errorf("Repositories.CreateUpdateEnvironment returned %+v, want %+v", release, want)
   200  	}
   201  
   202  	const methodName = "CreateUpdateEnvironment"
   203  	testBadOptions(t, methodName, func() (err error) {
   204  		_, _, err = client.Repositories.CreateUpdateEnvironment(ctx, "\n", "\n", "\n", input)
   205  		return err
   206  	})
   207  
   208  	testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {
   209  		got, resp, err := client.Repositories.CreateUpdateEnvironment(ctx, "o", "r", "e", input)
   210  		if got != nil {
   211  			t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got)
   212  		}
   213  		return resp, err
   214  	})
   215  }
   216  
   217  func TestRepositoriesService_DeleteEnvironment(t *testing.T) {
   218  	client, mux, _, teardown := setup()
   219  	defer teardown()
   220  
   221  	mux.HandleFunc("/repos/o/r/environments/e", func(w http.ResponseWriter, r *http.Request) {
   222  		testMethod(t, r, "DELETE")
   223  	})
   224  
   225  	ctx := context.Background()
   226  	_, err := client.Repositories.DeleteEnvironment(ctx, "o", "r", "e")
   227  	if err != nil {
   228  		t.Errorf("Repositories.DeleteEnvironment returned error: %v", err)
   229  	}
   230  
   231  	const methodName = "DeleteEnvironment"
   232  	testBadOptions(t, methodName, func() (err error) {
   233  		_, err = client.Repositories.DeleteEnvironment(ctx, "\n", "\n", "\n")
   234  		return err
   235  	})
   236  
   237  	testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {
   238  		return client.Repositories.DeleteEnvironment(ctx, "o", "r", "e")
   239  	})
   240  }
   241  
   242  func TestRepoEnvironment_Marshal(t *testing.T) {
   243  	testJSONMarshal(t, &EnvResponse{}, "{}")
   244  
   245  	repoEnv := &EnvResponse{
   246  		TotalCount: Int(1),
   247  		Environments: []*Environment{
   248  			{
   249  				Owner:           String("me"),
   250  				Repo:            String("se"),
   251  				EnvironmentName: String("dev"),
   252  				WaitTimer:       Int(123),
   253  				Reviewers: []*EnvReviewers{
   254  					{
   255  						Type: String("main"),
   256  						ID:   Int64(1),
   257  					},
   258  					{
   259  						Type: String("rev"),
   260  						ID:   Int64(2),
   261  					},
   262  				},
   263  				DeploymentBranchPolicy: &BranchPolicy{
   264  					ProtectedBranches:    Bool(false),
   265  					CustomBranchPolicies: Bool(false),
   266  				},
   267  				ID:        Int64(2),
   268  				NodeID:    String("star"),
   269  				Name:      String("eg"),
   270  				URL:       String("https://hey.in"),
   271  				HTMLURL:   String("htmlurl"),
   272  				CreatedAt: &Timestamp{referenceTime},
   273  				UpdatedAt: &Timestamp{referenceTime},
   274  				ProtectionRules: []*ProtectionRule{
   275  					{
   276  						ID:        Int64(21),
   277  						NodeID:    String("mnb"),
   278  						Type:      String("ewq"),
   279  						WaitTimer: Int(9090),
   280  					},
   281  				},
   282  			},
   283  		},
   284  	}
   285  
   286  	want := `{
   287  		"total_count":1,
   288  		"environments":[
   289  		   {
   290  			  "owner":"me",
   291  			  "repo":"se",
   292  			  "environment_name":"dev",
   293  			  "wait_timer":123,
   294  			  "reviewers":[
   295  				 {
   296  					"type":"main",
   297  					"id":1
   298  				 },
   299  				 {
   300  					"type":"rev",
   301  					"id":2
   302  				 }
   303  			  ],
   304  			  "deployment_branch_policy":{
   305  				 "protected_branches":false,
   306  				 "custom_branch_policies":false
   307  			  },
   308  			  "id":2,
   309  			  "node_id":"star",
   310  			  "name":"eg",
   311  			  "url":"https://hey.in",
   312  			  "html_url":"htmlurl",
   313  			  "created_at":` + referenceTimeStr + `,
   314  			  "updated_at":` + referenceTimeStr + `,
   315  			  "protection_rules":[
   316  				 {
   317  					"id":21,
   318  					"node_id":"mnb",
   319  					"type":"ewq",
   320  					"wait_timer":9090
   321  				 }
   322  			  ]
   323  		   }
   324  		]
   325  	 }`
   326  
   327  	testJSONMarshal(t, repoEnv, want)
   328  }
   329  
   330  func TestEnvReviewers_Marshal(t *testing.T) {
   331  	testJSONMarshal(t, &EnvReviewers{}, "{}")
   332  
   333  	repoEnv := &EnvReviewers{
   334  		Type: String("main"),
   335  		ID:   Int64(1),
   336  	}
   337  
   338  	want := `{
   339  		"type":"main",
   340  		"id":1
   341  	}`
   342  
   343  	testJSONMarshal(t, repoEnv, want)
   344  }
   345  
   346  func TestEnvironment_Marshal(t *testing.T) {
   347  	testJSONMarshal(t, &Environment{}, "{}")
   348  
   349  	repoEnv := &Environment{
   350  		Owner:           String("o"),
   351  		Repo:            String("r"),
   352  		EnvironmentName: String("e"),
   353  		WaitTimer:       Int(123),
   354  		Reviewers: []*EnvReviewers{
   355  			{
   356  				Type: String("main"),
   357  				ID:   Int64(1),
   358  			},
   359  			{
   360  				Type: String("rev"),
   361  				ID:   Int64(2),
   362  			},
   363  		},
   364  		DeploymentBranchPolicy: &BranchPolicy{
   365  			ProtectedBranches:    Bool(false),
   366  			CustomBranchPolicies: Bool(false),
   367  		},
   368  		ID:        Int64(2),
   369  		NodeID:    String("star"),
   370  		Name:      String("eg"),
   371  		URL:       String("https://hey.in"),
   372  		HTMLURL:   String("htmlurl"),
   373  		CreatedAt: &Timestamp{referenceTime},
   374  		UpdatedAt: &Timestamp{referenceTime},
   375  		ProtectionRules: []*ProtectionRule{
   376  			{
   377  				ID:        Int64(21),
   378  				NodeID:    String("mnb"),
   379  				Type:      String("ewq"),
   380  				WaitTimer: Int(9090),
   381  			},
   382  		},
   383  	}
   384  
   385  	want := `{
   386  		"owner":"o",
   387  		"repo":"r",
   388  		"environment_name":"e",
   389  		"wait_timer":123,
   390  		"reviewers":[
   391  			{
   392  				"type":"main",
   393  				"id":1
   394  			},
   395  			{
   396  				"type":"rev",
   397  				"id":2
   398  			}
   399  		],
   400  		"deployment_branch_policy":{
   401  			"protected_branches":false,
   402  			"custom_branch_policies":false
   403  		},
   404  		"id":2,
   405  		"node_id":"star",
   406  		"name":"eg",
   407  		"url":"https://hey.in",
   408  		"html_url":"htmlurl",
   409  		"created_at":` + referenceTimeStr + `,
   410  		"updated_at":` + referenceTimeStr + `,
   411  		"protection_rules":[
   412  			{
   413  				"id":21,
   414  				"node_id":"mnb",
   415  				"type":"ewq",
   416  				"wait_timer":9090
   417  			}
   418  		]
   419  	}`
   420  
   421  	testJSONMarshal(t, repoEnv, want)
   422  }