...

Source file src/github.com/google/go-github/v45/github/repos_environments_test.go

Documentation: github.com/google/go-github/v45/github

     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  	opt := &EnvironmentListOptions{
   112  		ListOptions: ListOptions{
   113  			Page:    2,
   114  			PerPage: 2,
   115  		},
   116  	}
   117  	ctx := context.Background()
   118  	environments, _, err := client.Repositories.ListEnvironments(ctx, "o", "r", opt)
   119  	if err != nil {
   120  		t.Errorf("Repositories.ListEnvironments returned error: %v", err)
   121  	}
   122  	want := &EnvResponse{TotalCount: Int(1), Environments: []*Environment{{ID: Int64(1)}, {ID: Int64(2)}}}
   123  	if !cmp.Equal(environments, want) {
   124  		t.Errorf("Repositories.ListEnvironments returned %+v, want %+v", environments, want)
   125  	}
   126  
   127  	const methodName = "ListEnvironments"
   128  	testBadOptions(t, methodName, func() (err error) {
   129  		_, _, err = client.Repositories.ListEnvironments(ctx, "\n", "\n", opt)
   130  		return err
   131  	})
   132  
   133  	testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {
   134  		got, resp, err := client.Repositories.ListEnvironments(ctx, "o", "r", opt)
   135  		if got != nil {
   136  			t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got)
   137  		}
   138  		return resp, err
   139  	})
   140  }
   141  
   142  func TestRepositoriesService_GetEnvironment(t *testing.T) {
   143  	client, mux, _, teardown := setup()
   144  	defer teardown()
   145  
   146  	mux.HandleFunc("/repos/o/r/environments/e", func(w http.ResponseWriter, r *http.Request) {
   147  		testMethod(t, r, "GET")
   148  		fmt.Fprint(w, `{"id": 1,"name": "staging", "deployment_branch_policy": {"protected_branches": true,	"custom_branch_policies": false}}`)
   149  	})
   150  
   151  	ctx := context.Background()
   152  	release, resp, err := client.Repositories.GetEnvironment(ctx, "o", "r", "e")
   153  	if err != nil {
   154  		t.Errorf("Repositories.GetEnvironment returned error: %v\n%v", err, resp.Body)
   155  	}
   156  
   157  	want := &Environment{ID: Int64(1), Name: String("staging"), DeploymentBranchPolicy: &BranchPolicy{ProtectedBranches: Bool(true), CustomBranchPolicies: Bool(false)}}
   158  	if !cmp.Equal(release, want) {
   159  		t.Errorf("Repositories.GetEnvironment returned %+v, want %+v", release, want)
   160  	}
   161  
   162  	const methodName = "GetEnvironment"
   163  	testBadOptions(t, methodName, func() (err error) {
   164  		_, _, err = client.Repositories.GetEnvironment(ctx, "\n", "\n", "\n")
   165  		return err
   166  	})
   167  
   168  	testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {
   169  		got, resp, err := client.Repositories.GetEnvironment(ctx, "o", "r", "e")
   170  		if got != nil {
   171  			t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got)
   172  		}
   173  		return resp, err
   174  	})
   175  }
   176  
   177  func TestRepositoriesService_CreateEnvironment(t *testing.T) {
   178  	client, mux, _, teardown := setup()
   179  	defer teardown()
   180  
   181  	input := &CreateUpdateEnvironment{
   182  		WaitTimer: Int(30),
   183  	}
   184  
   185  	mux.HandleFunc("/repos/o/r/environments/e", func(w http.ResponseWriter, r *http.Request) {
   186  		v := new(CreateUpdateEnvironment)
   187  		json.NewDecoder(r.Body).Decode(v)
   188  
   189  		testMethod(t, r, "PUT")
   190  		want := &CreateUpdateEnvironment{WaitTimer: Int(30)}
   191  		if !cmp.Equal(v, want) {
   192  			t.Errorf("Request body = %+v, want %+v", v, want)
   193  		}
   194  		fmt.Fprint(w, `{"id": 1, "name": "staging",	"protection_rules": [{"id": 1, "type": "wait_timer", "wait_timer": 30}]}`)
   195  	})
   196  
   197  	ctx := context.Background()
   198  	release, _, err := client.Repositories.CreateUpdateEnvironment(ctx, "o", "r", "e", input)
   199  	if err != nil {
   200  		t.Errorf("Repositories.CreateUpdateEnvironment returned error: %v", err)
   201  	}
   202  
   203  	want := &Environment{ID: Int64(1), Name: String("staging"), ProtectionRules: []*ProtectionRule{{ID: Int64(1), Type: String("wait_timer"), WaitTimer: Int(30)}}}
   204  	if !cmp.Equal(release, want) {
   205  		t.Errorf("Repositories.CreateUpdateEnvironment returned %+v, want %+v", release, want)
   206  	}
   207  
   208  	const methodName = "CreateUpdateEnvironment"
   209  	testBadOptions(t, methodName, func() (err error) {
   210  		_, _, err = client.Repositories.CreateUpdateEnvironment(ctx, "\n", "\n", "\n", input)
   211  		return err
   212  	})
   213  
   214  	testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {
   215  		got, resp, err := client.Repositories.CreateUpdateEnvironment(ctx, "o", "r", "e", input)
   216  		if got != nil {
   217  			t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got)
   218  		}
   219  		return resp, err
   220  	})
   221  }
   222  
   223  func TestRepositoriesService_DeleteEnvironment(t *testing.T) {
   224  	client, mux, _, teardown := setup()
   225  	defer teardown()
   226  
   227  	mux.HandleFunc("/repos/o/r/environments/e", func(w http.ResponseWriter, r *http.Request) {
   228  		testMethod(t, r, "DELETE")
   229  	})
   230  
   231  	ctx := context.Background()
   232  	_, err := client.Repositories.DeleteEnvironment(ctx, "o", "r", "e")
   233  	if err != nil {
   234  		t.Errorf("Repositories.DeleteEnvironment returned error: %v", err)
   235  	}
   236  
   237  	const methodName = "DeleteEnvironment"
   238  	testBadOptions(t, methodName, func() (err error) {
   239  		_, err = client.Repositories.DeleteEnvironment(ctx, "\n", "\n", "\n")
   240  		return err
   241  	})
   242  
   243  	testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {
   244  		return client.Repositories.DeleteEnvironment(ctx, "o", "r", "e")
   245  	})
   246  }
   247  
   248  func TestRepoEnvironment_Marshal(t *testing.T) {
   249  	testJSONMarshal(t, &EnvResponse{}, "{}")
   250  
   251  	repoEnv := &EnvResponse{
   252  		TotalCount: Int(1),
   253  		Environments: []*Environment{
   254  			{
   255  				Owner:           String("me"),
   256  				Repo:            String("se"),
   257  				EnvironmentName: String("dev"),
   258  				WaitTimer:       Int(123),
   259  				Reviewers: []*EnvReviewers{
   260  					{
   261  						Type: String("main"),
   262  						ID:   Int64(1),
   263  					},
   264  					{
   265  						Type: String("rev"),
   266  						ID:   Int64(2),
   267  					},
   268  				},
   269  				DeploymentBranchPolicy: &BranchPolicy{
   270  					ProtectedBranches:    Bool(false),
   271  					CustomBranchPolicies: Bool(false),
   272  				},
   273  				ID:        Int64(2),
   274  				NodeID:    String("star"),
   275  				Name:      String("eg"),
   276  				URL:       String("https://hey.in"),
   277  				HTMLURL:   String("htmlurl"),
   278  				CreatedAt: &Timestamp{referenceTime},
   279  				UpdatedAt: &Timestamp{referenceTime},
   280  				ProtectionRules: []*ProtectionRule{
   281  					{
   282  						ID:        Int64(21),
   283  						NodeID:    String("mnb"),
   284  						Type:      String("ewq"),
   285  						WaitTimer: Int(9090),
   286  					},
   287  				},
   288  			},
   289  		},
   290  	}
   291  
   292  	want := `{
   293  		"total_count":1,
   294  		"environments":[
   295  		   {
   296  			  "owner":"me",
   297  			  "repo":"se",
   298  			  "environment_name":"dev",
   299  			  "wait_timer":123,
   300  			  "reviewers":[
   301  				 {
   302  					"type":"main",
   303  					"id":1
   304  				 },
   305  				 {
   306  					"type":"rev",
   307  					"id":2
   308  				 }
   309  			  ],
   310  			  "deployment_branch_policy":{
   311  				 "protected_branches":false,
   312  				 "custom_branch_policies":false
   313  			  },
   314  			  "id":2,
   315  			  "node_id":"star",
   316  			  "name":"eg",
   317  			  "url":"https://hey.in",
   318  			  "html_url":"htmlurl",
   319  			  "created_at":` + referenceTimeStr + `,
   320  			  "updated_at":` + referenceTimeStr + `,
   321  			  "protection_rules":[
   322  				 {
   323  					"id":21,
   324  					"node_id":"mnb",
   325  					"type":"ewq",
   326  					"wait_timer":9090
   327  				 }
   328  			  ]
   329  		   }
   330  		]
   331  	 }`
   332  
   333  	testJSONMarshal(t, repoEnv, want)
   334  }
   335  
   336  func TestEnvReviewers_Marshal(t *testing.T) {
   337  	testJSONMarshal(t, &EnvReviewers{}, "{}")
   338  
   339  	repoEnv := &EnvReviewers{
   340  		Type: String("main"),
   341  		ID:   Int64(1),
   342  	}
   343  
   344  	want := `{
   345  		"type":"main",
   346  		"id":1
   347  	}`
   348  
   349  	testJSONMarshal(t, repoEnv, want)
   350  }
   351  
   352  func TestEnvironment_Marshal(t *testing.T) {
   353  	testJSONMarshal(t, &Environment{}, "{}")
   354  
   355  	repoEnv := &Environment{
   356  		Owner:           String("o"),
   357  		Repo:            String("r"),
   358  		EnvironmentName: String("e"),
   359  		WaitTimer:       Int(123),
   360  		Reviewers: []*EnvReviewers{
   361  			{
   362  				Type: String("main"),
   363  				ID:   Int64(1),
   364  			},
   365  			{
   366  				Type: String("rev"),
   367  				ID:   Int64(2),
   368  			},
   369  		},
   370  		DeploymentBranchPolicy: &BranchPolicy{
   371  			ProtectedBranches:    Bool(false),
   372  			CustomBranchPolicies: Bool(false),
   373  		},
   374  		ID:        Int64(2),
   375  		NodeID:    String("star"),
   376  		Name:      String("eg"),
   377  		URL:       String("https://hey.in"),
   378  		HTMLURL:   String("htmlurl"),
   379  		CreatedAt: &Timestamp{referenceTime},
   380  		UpdatedAt: &Timestamp{referenceTime},
   381  		ProtectionRules: []*ProtectionRule{
   382  			{
   383  				ID:        Int64(21),
   384  				NodeID:    String("mnb"),
   385  				Type:      String("ewq"),
   386  				WaitTimer: Int(9090),
   387  			},
   388  		},
   389  	}
   390  
   391  	want := `{
   392  		"owner":"o",
   393  		"repo":"r",
   394  		"environment_name":"e",
   395  		"wait_timer":123,
   396  		"reviewers":[
   397  			{
   398  				"type":"main",
   399  				"id":1
   400  			},
   401  			{
   402  				"type":"rev",
   403  				"id":2
   404  			}
   405  		],
   406  		"deployment_branch_policy":{
   407  			"protected_branches":false,
   408  			"custom_branch_policies":false
   409  		},
   410  		"id":2,
   411  		"node_id":"star",
   412  		"name":"eg",
   413  		"url":"https://hey.in",
   414  		"html_url":"htmlurl",
   415  		"created_at":` + referenceTimeStr + `,
   416  		"updated_at":` + referenceTimeStr + `,
   417  		"protection_rules":[
   418  			{
   419  				"id":21,
   420  				"node_id":"mnb",
   421  				"type":"ewq",
   422  				"wait_timer":9090
   423  			}
   424  		]
   425  	}`
   426  
   427  	testJSONMarshal(t, repoEnv, want)
   428  }
   429  

View as plain text