github.com/optim-corp/cios-golang-sdk@v0.5.1/sdk/service_account_group_test.go (about)

     1  package ciossdk
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"io/ioutil"
     7  	"math/rand"
     8  	"net/http"
     9  	"net/http/httptest"
    10  	"net/url"
    11  	"sync"
    12  	"testing"
    13  	"time"
    14  
    15  	srvaccount "github.com/optim-corp/cios-golang-sdk/sdk/service/account"
    16  
    17  	ciosctx "github.com/optim-corp/cios-golang-sdk/ctx"
    18  
    19  	xmath "github.com/fcfcqloow/go-advance/math"
    20  
    21  	cnv "github.com/fcfcqloow/go-advance/convert"
    22  
    23  	"github.com/optim-corp/cios-golang-sdk/cios"
    24  
    25  	sdkmodel "github.com/optim-corp/cios-golang-sdk/model"
    26  )
    27  
    28  // https://auth0.com/docs/tokens/access-tokens/use-access-tokens
    29  var sampleToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2V4YW1wbGUuYXV0aDAuY29tLyIsImF1ZCI6Imh0dHBzOi8vYXBpLmV4YW1wbGUuY29tL2NhbGFuZGFyL3YxLyIsInN1YiI6InVzcl8xMjMiLCJpYXQiOjE0NTg3ODU3OTYsImV4cCI6MTQ1ODg3MjE5Nn0.CA7eaHjIHz5NxeIJoFK9krqaeZrPLwmMmgI_XiQiIkQ"
    30  
    31  func Test_RefreshGroup(t *testing.T) {
    32  	count, _token, ctx := 0, "", context.Background()
    33  	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    34  		w.Header().Set("Content-Type", "application/json")
    35  		_token = r.Header.Get("Authorization")
    36  		if r.URL.Path == "/connect/token" {
    37  			count += 1
    38  			json.NewEncoder(w).Encode(cios.ConnectTokenResponse{
    39  				AccessToken:  sampleToken,
    40  				TokenType:    "",
    41  				RefreshToken: "",
    42  				ExpiresIn:    0,
    43  				Scope:        "",
    44  			})
    45  		}
    46  		if r.URL.Path == "/v2/groups" && r.Method == http.MethodGet {
    47  			time.Sleep(time.Microsecond * time.Duration(rand.Int63n(1000)))
    48  			json.NewEncoder(w).Encode(cios.MultipleGroup{
    49  				Groups: []cios.Group{
    50  					{
    51  						Id: r.URL.Query().Get("name") + ":" + r.Header.Get("Authorization"),
    52  					},
    53  				},
    54  			})
    55  		}
    56  	})
    57  	ts := httptest.NewServer(handler)
    58  	client := NewCiosClient(CiosClientConfig{
    59  		AutoRefresh: true,
    60  		Urls:        sdkmodel.CIOSUrl{AccountsUrl: ts.URL, AuthUrl: ts.URL},
    61  		AuthConfig: RefreshTokenAuth(
    62  			"clientID",
    63  			"clientSecret",
    64  			"assertion",
    65  			"scope",
    66  		),
    67  	})
    68  	funcs := []func(){
    69  		func() { client.Account().GetGroups(ctx, srvaccount.MakeGetGroupsOpts()) },
    70  		func() { client.Account().CreateGroup(ctx, cios.GroupCreateRequest{}) },
    71  		func() { client.Account().GetGroup(ctx, "", nil) },
    72  		func() { client.Account().UpdateGroup(ctx, "", cios.GroupUpdateRequest{}) },
    73  		func() { client.Account().DeleteGroup(ctx, "") },
    74  	}
    75  	for i, fnc := range funcs {
    76  		fnc()
    77  		if _token != "Bearer "+sampleToken {
    78  			t.Fatal(_token)
    79  		}
    80  		if count != i+1 {
    81  			t.Fatal(count)
    82  		}
    83  		_token = ""
    84  	}
    85  	for _, fnc := range funcs {
    86  		client.SetTokenExp(time.Now().Unix() + 10000)
    87  		fnc()
    88  		if _token != "Bearer "+sampleToken {
    89  			t.Fatal(_token)
    90  		}
    91  		if count != len(funcs) {
    92  			t.Fatal(count)
    93  		}
    94  		_token = ""
    95  	}
    96  
    97  	ctx = ciosctx.WithToken(ctx, "AAA")
    98  	count = 0
    99  	_token = ""
   100  	client = NewCiosClient(CiosClientConfig{
   101  		AutoRefresh: true,
   102  		Urls:        sdkmodel.CIOSUrl{AccountsUrl: ts.URL, AuthUrl: ts.URL},
   103  		AuthConfig: RefreshTokenAuth(
   104  			"clientID",
   105  			"clientSecret",
   106  			"assertion",
   107  			"scope",
   108  		),
   109  	})
   110  
   111  	// リクエストごとのトークンを識別しているかテスト
   112  	wg := sync.WaitGroup{}
   113  	asyncTestNumber := 10 // 非同期にリクエストする回数
   114  	wg.Add(asyncTestNumber)
   115  	for i := 0; i < asyncTestNumber; i++ {
   116  		go func(i int) {
   117  			time.Sleep(time.Microsecond * time.Duration(rand.Int63n(100)))
   118  			response, _, _ := client.Account().GetGroups(ciosctx.WithToken(nil, cnv.MustStr(i)), srvaccount.MakeGetGroupsOpts().Name("async "+cnv.MustStr(i)))
   119  			if response.Groups[0].Id != "async "+cnv.MustStr(i)+":Bearer "+cnv.MustStr(i) {
   120  				t.Fatal(response.Groups)
   121  			}
   122  			t.Log(response)
   123  			wg.Done()
   124  		}(i)
   125  	}
   126  	wg.Wait()
   127  }
   128  func TestAccount_Groups(t *testing.T) {
   129  	var (
   130  		query url.Values
   131  		ctx   context.Context
   132  
   133  		tests = []struct {
   134  			params cios.ApiGetGroupsRequest
   135  			test   func()
   136  		}{
   137  			{
   138  				params: srvaccount.MakeGetGroupsOpts().Limit(1000),
   139  				test: func() {
   140  					if query.Get("limit") != "1000" {
   141  						t.Fatal("Missing Query", query.Encode())
   142  					} else {
   143  						t.Log(query.Encode())
   144  					}
   145  				},
   146  			},
   147  			{
   148  				params: srvaccount.MakeGetGroupsOpts().Limit(1000).Offset(50),
   149  				test: func() {
   150  					if query.Get("limit") != "1000" || query.Get("offset") != "50" {
   151  						t.Fatal("Missing Query", query.Encode())
   152  					} else {
   153  						t.Log(query.Encode())
   154  					}
   155  				},
   156  			},
   157  			{
   158  				params: srvaccount.MakeGetGroupsOpts().Limit(1000).Offset(50).Name("name"),
   159  				test: func() {
   160  					if query.Get("name") != "name" {
   161  						t.Fatal("Missing Query", query.Encode())
   162  					} else {
   163  						t.Log(query.Encode())
   164  					}
   165  				},
   166  			},
   167  			{
   168  				params: srvaccount.MakeGetGroupsOpts().OrderBy("created_at"),
   169  				test: func() {
   170  					if query.Get("order_by") != "created_at" {
   171  						t.Fatal("Missing Query", query.Encode())
   172  					} else {
   173  						t.Log(query.Encode())
   174  					}
   175  				},
   176  			},
   177  			{
   178  				params: srvaccount.MakeGetGroupsOpts().
   179  					OrderBy("").
   180  					Order("").
   181  					Name("").
   182  					Label("").
   183  					Page("").
   184  					Address1("").
   185  					Address2("").
   186  					City("").
   187  					Tags("").Domain("").Includes("").State("").ParentGroupId("").Type_(""),
   188  				test: func() {
   189  					if query.Encode() != "" {
   190  						t.Fatal("Missing Query", query.Encode())
   191  					} else {
   192  						t.Log(query.Encode())
   193  					}
   194  				},
   195  			},
   196  		}
   197  	)
   198  	// Query Test
   199  	responseHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   200  		w.Header().Set("Content-Type", "application/json")
   201  		query = r.URL.Query()
   202  		json.NewEncoder(w).Encode(cios.MultipleGroup{Total: 10})
   203  	})
   204  	ts := httptest.NewServer(responseHandler)
   205  
   206  	client := NewCiosClient(CiosClientConfig{Urls: sdkmodel.CIOSUrl{AccountsUrl: ts.URL}})
   207  
   208  	defer ts.Close()
   209  	for _, test := range tests {
   210  		client.Account().GetGroups(ctx, test.params)
   211  		test.test()
   212  	}
   213  
   214  	ts.Close()
   215  }
   216  
   217  func TestAccount_GetGroupsAll(t *testing.T) {
   218  	var offsets []int
   219  	var limits []int
   220  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   221  		w.Header().Set("Content-Type", "application/json")
   222  		response := cios.MultipleGroup{Total: 3500, Groups: []cios.Group{}}
   223  		offset := cnv.MustInt(r.URL.Query().Get("offset"))
   224  		limit := cnv.MustInt(r.URL.Query().Get("limit"))
   225  		offsets = append(offsets, offset)
   226  		limits = append(limits, limit)
   227  		for i := 0; i < xmath.MinInt(3500-offset, 1000, limit); i++ {
   228  			response.Groups = append(response.Groups, cios.Group{Id: cnv.MustStr(i)})
   229  		}
   230  		json.NewEncoder(w).Encode(response)
   231  	}))
   232  	defer ts.Close()
   233  	client := NewCiosClient(CiosClientConfig{Urls: sdkmodel.CIOSUrl{AccountsUrl: ts.URL}})
   234  
   235  	responses, _, _ := client.Account().GetGroupsAll(nil, srvaccount.MakeGetGroupsOpts().Limit(999))
   236  	if len(responses) != 999 || offsets[0] != 0 && limits[0] != 1000 {
   237  		t.Fatal(len(responses))
   238  	}
   239  
   240  	offsets = []int{}
   241  	limits = []int{}
   242  	responses, _, _ = client.Account().GetGroupsAll(nil, srvaccount.MakeGetGroupsOpts().Limit(1500))
   243  	if len(responses) != 1500 || offsets[0] != 0 && limits[0] != 1000 || offsets[1] != 1000 && limits[1] != 1000 {
   244  		t.Fatal(len(responses), limits, offsets)
   245  	}
   246  	offsets = []int{}
   247  	limits = []int{}
   248  	responses, _, _ = client.Account().GetGroupsAll(nil, srvaccount.MakeGetGroupsOpts().Limit(2001))
   249  	if len(responses) != 2001 || offsets[0] != 0 && limits[0] != 1000 || offsets[1] != 1000 && limits[1] != 1000 || offsets[2] != 2000 || limits[2] != 1 {
   250  		t.Fatal(len(responses), limits, offsets)
   251  
   252  	}
   253  	offsets = []int{}
   254  	limits = []int{}
   255  	responses, _, _ = client.Account().GetGroupsAll(nil, srvaccount.MakeGetGroupsOpts().Limit(3501))
   256  	if len(responses) != 3500 ||
   257  		offsets[0] != 0 || limits[0] != 1000 ||
   258  		offsets[1] != 1000 && limits[1] != 1000 ||
   259  		offsets[2] != 2000 || limits[2] != 1000 ||
   260  		offsets[3] != 3000 || limits[3] != 501 {
   261  		t.Fatal(len(responses), limits, offsets)
   262  	}
   263  	offsets = []int{}
   264  	limits = []int{}
   265  	responses, _, _ = client.Account().GetGroupsAll(nil, srvaccount.MakeGetGroupsOpts().Limit(2001).Offset(20))
   266  	if len(responses) != 2001 || offsets[0] != 20 && limits[0] != 1000 || offsets[1] != 1020 && limits[1] != 1000 || offsets[2] != 2020 || limits[2] != 1 {
   267  		t.Fatal(len(responses), limits, offsets)
   268  
   269  	}
   270  }
   271  
   272  func TestAccount_GetGroupsUnlimited(t *testing.T) {
   273  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   274  		w.Header().Set("Content-Type", "application/json")
   275  		response := cios.MultipleGroup{Total: 3500, Groups: []cios.Group{}}
   276  		offset := cnv.MustInt(r.URL.Query().Get("offset"))
   277  		limit := cnv.MustInt(r.URL.Query().Get("limit"))
   278  		for i := 0; i < xmath.MinInt(3500-offset, 1000, limit); i++ {
   279  			response.Groups = append(response.Groups, cios.Group{Id: cnv.MustStr(i)})
   280  		}
   281  		json.NewEncoder(w).Encode(response)
   282  	}))
   283  	defer ts.Close()
   284  	client := NewCiosClient(CiosClientConfig{Urls: sdkmodel.CIOSUrl{AccountsUrl: ts.URL}})
   285  
   286  	response, _, _ := client.Account().GetGroupsUnlimited(nil, srvaccount.MakeGetGroupsOpts().Limit(1))
   287  	if len(response) != 3500 {
   288  		t.Fatal(len(response))
   289  	}
   290  }
   291  
   292  func TestAccount_GetGroup(t *testing.T) {
   293  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   294  		w.Header().Set("Content-Type", "application/json")
   295  		if r.Method != "GET" {
   296  			t.Fatal(r.Method)
   297  		}
   298  		if r.URL.Path == "/v2/groups/test" {
   299  			response := cios.Group{
   300  				Id:   "test",
   301  				Name: "",
   302  			}
   303  			json.NewEncoder(w).Encode(response)
   304  		}
   305  	}))
   306  	defer ts.Close()
   307  	client := NewCiosClient(CiosClientConfig{Urls: sdkmodel.CIOSUrl{AccountsUrl: ts.URL}})
   308  	responseB, response, err := client.Account().GetGroup(nil, "test", nil)
   309  	if responseB.Id != "test" || err != nil || response.StatusCode != 200 {
   310  		t.Fatal(responseB)
   311  	}
   312  }
   313  
   314  func TestAccount_CreateGroup(t *testing.T) {
   315  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   316  		w.Header().Set("Content-Type", "application/json")
   317  		if r.URL.Path != "/v2/groups" {
   318  			t.Fatal(r.URL.Path)
   319  		}
   320  		body := cios.GroupCreateRequest{}
   321  		if r.Method != "POST" {
   322  			t.Fatal(r.Method)
   323  		}
   324  		byts, _ := ioutil.ReadAll(r.Body)
   325  		cnv.UnMarshalJson(byts, &body)
   326  		if body.Name != "name" ||
   327  			*body.ParentGroupId != "parent" ||
   328  			(*body.Tags)[0] != "key=value" {
   329  			t.Fatal(body)
   330  		}
   331  
   332  	}))
   333  	defer ts.Close()
   334  	client := NewCiosClient(CiosClientConfig{Urls: sdkmodel.CIOSUrl{AccountsUrl: ts.URL}})
   335  	_, _, err := client.Account().CreateGroup(nil, cios.GroupCreateRequest{
   336  		ParentGroupId: cnv.StrPtr("parent"),
   337  		Name:          "name",
   338  		Tags:          &[]string{"key=value", "a=b"},
   339  	})
   340  	if err != nil {
   341  		t.Fatal(err.Error())
   342  	}
   343  }
   344  
   345  func TestAccount_DeleteGroup(t *testing.T) {
   346  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   347  		w.Header().Set("Content-Type", "application/json")
   348  		if r.URL.Path != "/v2/groups/id" {
   349  			t.Fatal(r.URL.Path)
   350  		}
   351  		if r.Method != "DELETE" {
   352  			t.Fatal(r.Method)
   353  		}
   354  	}))
   355  	defer ts.Close()
   356  	client := NewCiosClient(CiosClientConfig{Urls: sdkmodel.CIOSUrl{AccountsUrl: ts.URL}})
   357  	_, err := client.Account().DeleteGroup(nil, "id")
   358  	if err != nil {
   359  		t.Fatal(err.Error())
   360  	}
   361  }
   362  func TestAccount_UpdateGroup(t *testing.T) {
   363  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   364  		w.Header().Set("Content-Type", "application/json")
   365  		if r.URL.Path != "/v2/groups/id" {
   366  			t.Fatal(r.URL.Path)
   367  		}
   368  		if r.Method != "PATCH" {
   369  			t.Fatal(r.Method)
   370  		}
   371  	}))
   372  	defer ts.Close()
   373  	client := NewCiosClient(CiosClientConfig{Urls: sdkmodel.CIOSUrl{AccountsUrl: ts.URL}})
   374  	_, _, err := client.Account().UpdateGroup(nil, "id", cios.GroupUpdateRequest{
   375  		Name: cnv.StrPtr("name"),
   376  	})
   377  	if err != nil {
   378  		t.Fatal(err.Error())
   379  	}
   380  }