You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

88 lines
2.3 KiB

  1. // Copyright 2016 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package iam
  15. import (
  16. "fmt"
  17. "sort"
  18. "testing"
  19. "cloud.google.com/go/internal/testutil"
  20. )
  21. func TestPolicy(t *testing.T) {
  22. p := &Policy{}
  23. add := func(member string, role RoleName) {
  24. p.Add(member, role)
  25. }
  26. remove := func(member string, role RoleName) {
  27. p.Remove(member, role)
  28. }
  29. if msg, ok := checkMembers(p, Owner, nil); !ok {
  30. t.Fatal(msg)
  31. }
  32. add("m1", Owner)
  33. if msg, ok := checkMembers(p, Owner, []string{"m1"}); !ok {
  34. t.Fatal(msg)
  35. }
  36. add("m2", Owner)
  37. if msg, ok := checkMembers(p, Owner, []string{"m1", "m2"}); !ok {
  38. t.Fatal(msg)
  39. }
  40. add("m1", Owner) // duplicate adds ignored
  41. if msg, ok := checkMembers(p, Owner, []string{"m1", "m2"}); !ok {
  42. t.Fatal(msg)
  43. }
  44. // No other roles populated yet.
  45. if msg, ok := checkMembers(p, Viewer, nil); !ok {
  46. t.Fatal(msg)
  47. }
  48. remove("m1", Owner)
  49. if msg, ok := checkMembers(p, Owner, []string{"m2"}); !ok {
  50. t.Fatal(msg)
  51. }
  52. if msg, ok := checkMembers(p, Viewer, nil); !ok {
  53. t.Fatal(msg)
  54. }
  55. remove("m3", Owner) // OK to remove non-existent member.
  56. if msg, ok := checkMembers(p, Owner, []string{"m2"}); !ok {
  57. t.Fatal(msg)
  58. }
  59. remove("m2", Owner)
  60. if msg, ok := checkMembers(p, Owner, nil); !ok {
  61. t.Fatal(msg)
  62. }
  63. if got, want := p.Roles(), []RoleName(nil); !testutil.Equal(got, want) {
  64. t.Fatalf("roles: got %v, want %v", got, want)
  65. }
  66. }
  67. func checkMembers(p *Policy, role RoleName, wantMembers []string) (string, bool) {
  68. gotMembers := p.Members(role)
  69. sort.Strings(gotMembers)
  70. sort.Strings(wantMembers)
  71. if !testutil.Equal(gotMembers, wantMembers) {
  72. return fmt.Sprintf("got %v, want %v", gotMembers, wantMembers), false
  73. }
  74. for _, m := range wantMembers {
  75. if !p.HasRole(m, role) {
  76. return fmt.Sprintf("member %q should have role %s but does not", m, role), false
  77. }
  78. }
  79. return "", true
  80. }