|
| 1 | +package google |
| 2 | + |
| 3 | +import ( |
| 4 | + "google.golang.org/api/cloudresourcemanager/v1" |
| 5 | + "google.golang.org/api/googleapi" |
| 6 | + "testing" |
| 7 | +) |
| 8 | + |
| 9 | +// Mock ResourceIamUpdater |
| 10 | +type readTestUpdater struct { |
| 11 | + errorCode int |
| 12 | + returnAfterAttempts int |
| 13 | + numAttempts int |
| 14 | +} |
| 15 | + |
| 16 | +// Not being tested |
| 17 | +func (u *readTestUpdater) SetResourceIamPolicy(p *cloudresourcemanager.Policy) error { return nil } |
| 18 | +func (u *readTestUpdater) GetMutexKey() string { return "a-resource-key" } |
| 19 | +func (u *readTestUpdater) GetResourceId() string { return "id" } |
| 20 | +func (u *readTestUpdater) DescribeResource() string { return "mock updater" } |
| 21 | + |
| 22 | +// Fetch the existing IAM policy attached to a resource. |
| 23 | +func (u *readTestUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) { |
| 24 | + u.numAttempts++ |
| 25 | + if u.numAttempts < u.returnAfterAttempts { |
| 26 | + // Indicate retry |
| 27 | + return nil, &googleapi.Error{Code: 429} |
| 28 | + } |
| 29 | + |
| 30 | + // Was testing successes or was testing retryable |
| 31 | + if u.errorCode == 200 { |
| 32 | + return &cloudresourcemanager.Policy{}, nil |
| 33 | + } |
| 34 | + return nil, &googleapi.Error{Code: u.errorCode} |
| 35 | +} |
| 36 | + |
| 37 | +func TestIamPolicyReadWithRetry_returnImmediately(t *testing.T) { |
| 38 | + mockUpdater := &readTestUpdater{ |
| 39 | + returnAfterAttempts: 1, |
| 40 | + errorCode: 200, |
| 41 | + } |
| 42 | + p, err := iamPolicyReadWithRetry(mockUpdater) |
| 43 | + if err != nil || p == nil { |
| 44 | + t.Errorf("expected valid policy and no error, got nil policy and error %v", err) |
| 45 | + } |
| 46 | + if mockUpdater.numAttempts != 1 { |
| 47 | + t.Errorf("expected GetResourceIamPolicy to have been called once") |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +func TestIamPolicyReadWithRetry_retry(t *testing.T) { |
| 52 | + mockUpdater := &readTestUpdater{ |
| 53 | + returnAfterAttempts: 3, |
| 54 | + errorCode: 404, |
| 55 | + } |
| 56 | + p, err := iamPolicyReadWithRetry(mockUpdater) |
| 57 | + if err == nil || !isGoogleApiErrorWithCode(err, 404) { |
| 58 | + t.Errorf("expected googleapi error 404, got policy %v, err %v", p, err) |
| 59 | + } |
| 60 | + if mockUpdater.numAttempts != mockUpdater.returnAfterAttempts { |
| 61 | + t.Errorf("expected GetResourceIamPolicy to have been called %d times, was called %d", mockUpdater.numAttempts, mockUpdater.returnAfterAttempts) |
| 62 | + } |
| 63 | +} |
0 commit comments