github.com/clerkinc/clerk-sdk-go@v1.49.1/clerk/organizations_test.go (about)

     1  package clerk
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"net/http"
     8  	"net/url"
     9  	"os"
    10  	"path"
    11  	"reflect"
    12  	"strings"
    13  	"testing"
    14  
    15  	"github.com/stretchr/testify/assert"
    16  )
    17  
    18  func TestOrganizationsService_Read(t *testing.T) {
    19  	client, mux, _, teardown := setup("token")
    20  	defer teardown()
    21  
    22  	expectedResponse := dummyOrganizationJson
    23  	orgID := "randomIDorSlug"
    24  
    25  	mux.HandleFunc(fmt.Sprintf("/organizations/%s", orgID), func(w http.ResponseWriter, req *http.Request) {
    26  		testHttpMethod(t, req, "GET")
    27  		testHeader(t, req, "Authorization", "Bearer token")
    28  		fmt.Fprint(w, expectedResponse)
    29  	})
    30  
    31  	got, err := client.Organizations().Read(orgID)
    32  	if err != nil {
    33  		t.Fatal(err)
    34  	}
    35  
    36  	var want Organization
    37  	err = json.Unmarshal([]byte(expectedResponse), &want)
    38  	if err != nil {
    39  		t.Fatal(err)
    40  	}
    41  
    42  	if !reflect.DeepEqual(got, &want) {
    43  		t.Errorf("Response = %v, want %v", got, &want)
    44  	}
    45  }
    46  
    47  func TestOrganizationsService_Update(t *testing.T) {
    48  	client, mux, _, teardown := setup("token")
    49  	defer teardown()
    50  	var payload UpdateOrganizationParams
    51  	_ = json.Unmarshal([]byte(dummyUpdateOrganizationJson), &payload)
    52  
    53  	expectedResponse := dummyOrganizationJson
    54  	orgID := "randomIDorSlug"
    55  
    56  	mux.HandleFunc(fmt.Sprintf("/organizations/%s", orgID), func(w http.ResponseWriter, req *http.Request) {
    57  		testHttpMethod(t, req, "PATCH")
    58  		testHeader(t, req, "Authorization", "Bearer token")
    59  		fmt.Fprint(w, expectedResponse)
    60  	})
    61  
    62  	got, err := client.Organizations().Update(orgID, payload)
    63  	if err != nil {
    64  		t.Fatal(err)
    65  	}
    66  
    67  	var want Organization
    68  	err = json.Unmarshal([]byte(expectedResponse), &want)
    69  	if err != nil {
    70  		t.Fatal(err)
    71  	}
    72  
    73  	if !reflect.DeepEqual(got, &want) {
    74  		t.Errorf("Response = %v, want %v", got, &want)
    75  	}
    76  }
    77  
    78  func TestOrganizationsService_invalidServer(t *testing.T) {
    79  	client, _ := NewClient("token")
    80  	var payload UpdateOrganizationParams
    81  	_ = json.Unmarshal([]byte(dummyUpdateOrganizationJson), &payload)
    82  
    83  	_, err := client.Organizations().Update("someOrgId", payload)
    84  	if err == nil {
    85  		t.Errorf("Expected error to be returned")
    86  	}
    87  }
    88  
    89  func TestOrganizationsService_ListAll_happyPath(t *testing.T) {
    90  	client, mux, _, teardown := setup("token")
    91  	defer teardown()
    92  
    93  	expectedResponse := fmt.Sprintf(`{
    94  		"data": [%s],
    95  		"total_count": 1
    96  	}`, dummyOrganizationJson)
    97  
    98  	mux.HandleFunc("/organizations", func(w http.ResponseWriter, req *http.Request) {
    99  		testHttpMethod(t, req, "GET")
   100  		testHeader(t, req, "Authorization", "Bearer token")
   101  		fmt.Fprint(w, expectedResponse)
   102  	})
   103  
   104  	var want *OrganizationsResponse
   105  	_ = json.Unmarshal([]byte(expectedResponse), &want)
   106  
   107  	got, _ := client.Organizations().ListAll(ListAllOrganizationsParams{})
   108  	if len(got.Data) != len(want.Data) {
   109  		t.Errorf("Was expecting %d organizations to be returned, instead got %d", len(want.Data), len(got.Data))
   110  	}
   111  
   112  	if !reflect.DeepEqual(got, want) {
   113  		t.Errorf("Response = %v, want %v", got, want)
   114  	}
   115  }
   116  
   117  func TestOrganizationsService_ListAll_happyPathWithParameters(t *testing.T) {
   118  	client, mux, _, teardown := setup("token")
   119  	defer teardown()
   120  
   121  	expectedResponse := fmt.Sprintf(`{
   122  		"data": [%s],
   123  		"total_count": 1
   124  	}`, dummyOrganizationJson)
   125  
   126  	mux.HandleFunc("/organizations", func(w http.ResponseWriter, req *http.Request) {
   127  		testHttpMethod(t, req, "GET")
   128  		testHeader(t, req, "Authorization", "Bearer token")
   129  
   130  		actualQuery := req.URL.Query()
   131  		expectedQuery := url.Values(map[string][]string{
   132  			"limit":                 {"5"},
   133  			"offset":                {"6"},
   134  			"include_members_count": {"true"},
   135  		})
   136  		assert.Equal(t, expectedQuery, actualQuery)
   137  		fmt.Fprint(w, expectedResponse)
   138  	})
   139  
   140  	var want *OrganizationsResponse
   141  	_ = json.Unmarshal([]byte(expectedResponse), &want)
   142  
   143  	limit := 5
   144  	offset := 6
   145  	got, _ := client.Organizations().ListAll(ListAllOrganizationsParams{
   146  		Limit:               &limit,
   147  		Offset:              &offset,
   148  		IncludeMembersCount: true,
   149  	})
   150  	if len(got.Data) != len(want.Data) {
   151  		t.Errorf("Was expecting %d organizations to be returned, instead got %d", len(want.Data), len(got.Data))
   152  	}
   153  
   154  	if !reflect.DeepEqual(got, want) {
   155  		t.Errorf("Response = %v, want %v", got, want)
   156  	}
   157  }
   158  
   159  func TestOrganizationsService_ListAll_happyPathWithQuery(t *testing.T) {
   160  	client, mux, _, teardown := setup("token")
   161  	defer teardown()
   162  
   163  	expectedResponse := fmt.Sprintf(`{
   164  		"data": [%s],
   165  		"total_count": 1
   166  	}`, dummyOrganizationJson)
   167  
   168  	mux.HandleFunc("/organizations", func(w http.ResponseWriter, req *http.Request) {
   169  		testHttpMethod(t, req, "GET")
   170  		testHeader(t, req, "Authorization", "Bearer token")
   171  
   172  		actualQuery := req.URL.Query()
   173  		expectedQuery := url.Values(map[string][]string{
   174  			"query": {"test"},
   175  		})
   176  		assert.Equal(t, expectedQuery, actualQuery)
   177  		fmt.Fprint(w, expectedResponse)
   178  	})
   179  
   180  	var want *OrganizationsResponse
   181  	_ = json.Unmarshal([]byte(expectedResponse), &want)
   182  	got, _ := client.Organizations().ListAll(ListAllOrganizationsParams{
   183  		Query: "test",
   184  	})
   185  	if len(got.Data) != len(want.Data) {
   186  		t.Errorf("Was expecting %d organizations to be returned, instead got %d", len(want.Data), len(got.Data))
   187  	}
   188  
   189  	if !reflect.DeepEqual(got, want) {
   190  		t.Errorf("Response = %v, want %v", got, want)
   191  	}
   192  }
   193  
   194  func TestOrganizationsService_ListAll_invalidServer(t *testing.T) {
   195  	client, _ := NewClient("token")
   196  
   197  	organizations, err := client.Organizations().ListAll(ListAllOrganizationsParams{})
   198  	if err == nil {
   199  		t.Errorf("Expected error to be returned")
   200  	}
   201  	if organizations != nil {
   202  		t.Errorf("Was not expecting any organizations to be returned, instead got %v", organizations)
   203  	}
   204  }
   205  
   206  func TestOrganizationsService_UpdateLogo(t *testing.T) {
   207  	client, mux, _, teardown := setup("token")
   208  	defer teardown()
   209  
   210  	organizationID := "org_123"
   211  	uploaderUserID := "user_123"
   212  	expectedResponse := fmt.Sprintf(`{"id":"%s"}`, organizationID)
   213  	filename := "200x200-grayscale.jpg"
   214  	file, err := os.Open(path.Join("..", "testdata", filename))
   215  	if err != nil {
   216  		t.Fatal(err)
   217  	}
   218  	defer file.Close()
   219  
   220  	mux.HandleFunc(
   221  		fmt.Sprintf("/organizations/%s/logo", organizationID),
   222  		func(w http.ResponseWriter, req *http.Request) {
   223  			testHttpMethod(t, req, http.MethodPut)
   224  			testHeader(t, req, "Authorization", "Bearer token")
   225  			// Assert that the request is sent as multipart/form-data
   226  			if !strings.Contains(req.Header["Content-Type"][0], "multipart/form-data") {
   227  				t.Errorf("expected content-type to be multipart/form-data, got %s", req.Header["Content-Type"])
   228  			}
   229  			defer req.Body.Close()
   230  
   231  			// Check that the file is sent correctly
   232  			fileParam, header, err := req.FormFile("file")
   233  			if err != nil {
   234  				t.Fatal(err)
   235  			}
   236  			if header.Filename != filename {
   237  				t.Errorf("expected %s, got %s", filename, header.Filename)
   238  			}
   239  			defer fileParam.Close()
   240  
   241  			got := make([]byte, header.Size)
   242  			gotSize, err := fileParam.Read(got)
   243  			if err != nil {
   244  				t.Fatal(err)
   245  			}
   246  			fileInfo, err := file.Stat()
   247  			if err != nil {
   248  				t.Fatal(err)
   249  			}
   250  			want := make([]byte, fileInfo.Size())
   251  			_, err = file.Seek(0, 0)
   252  			if err != nil {
   253  				t.Fatal(err)
   254  			}
   255  			wantSize, err := file.Read(want)
   256  			if err != nil {
   257  				t.Fatal(err)
   258  			}
   259  			if gotSize != wantSize {
   260  				t.Errorf("read different size of files")
   261  			}
   262  			if !bytes.Equal(got, want) {
   263  				t.Errorf("file was not sent correctly")
   264  			}
   265  
   266  			// Check the uploader user ID
   267  			if got, ok := req.MultipartForm.Value["uploader_user_id"]; !ok || got[0] != uploaderUserID {
   268  				t.Errorf("expected %s, got %s", uploaderUserID, got)
   269  			}
   270  
   271  			fmt.Fprint(w, expectedResponse)
   272  		},
   273  	)
   274  
   275  	// Trigger a request to update the logo with the file
   276  	org, err := client.Organizations().UpdateLogo(organizationID, UpdateOrganizationLogoParams{
   277  		File:           file,
   278  		Filename:       &filename,
   279  		UploaderUserID: "user_123",
   280  	})
   281  	if err != nil {
   282  		t.Fatal(err)
   283  	}
   284  	if org.ID != organizationID {
   285  		t.Errorf("expected %s, got %s", organizationID, org.ID)
   286  	}
   287  }
   288  
   289  func TestOrganizationsService_DeleteLogo(t *testing.T) {
   290  	client, mux, _, teardown := setup("token")
   291  	defer teardown()
   292  
   293  	organizationID := "org_123"
   294  	mux.HandleFunc(
   295  		fmt.Sprintf("/organizations/%s/logo", organizationID),
   296  		func(w http.ResponseWriter, req *http.Request) {
   297  			testHttpMethod(t, req, http.MethodDelete)
   298  			testHeader(t, req, "Authorization", "Bearer token")
   299  			fmt.Fprint(w, fmt.Sprintf(`{"id":"%s"}`, organizationID))
   300  		},
   301  	)
   302  
   303  	// Trigger a request to delete the logo
   304  	_, err := client.Organizations().DeleteLogo(organizationID)
   305  	if err != nil {
   306  		t.Fatal(err)
   307  	}
   308  }
   309  
   310  const dummyOrganizationJson = `{
   311  	"object": "organization",
   312  	"id": "org_1mebQggrD3xO5JfuHk7clQ94ysA",
   313  	"name": "test-org",
   314  	"slug": "org_slug",
   315  	"members_count": 42,
   316  	"created_by": "user_1mebQggrD3xO5JfuHk7clQ94ysA",
   317  	"created_at": 1610783813,
   318  	"updated_at": 1610783813,
   319  	"public_metadata": {
   320  		"address": {
   321  			"street": "Pennsylvania Avenue",
   322  			"number": "1600"
   323  		}
   324  	},
   325  	"private_metadata": {
   326  		"app_id": 5
   327  	}
   328  }`
   329  
   330  const dummyUpdateOrganizationJson = `{
   331  	"object": "organization",
   332  	"id": "org_1mebQggrD3xO5JfuHk7clQ94ysA",
   333  	"name": "test-org",
   334  	"slug": "org_slug",
   335  	"members_count": 42,
   336  	"created_by": "user_1mebQggrD3xO5JfuHk7clQ94ysA",
   337  	"created_at": 1610783813,
   338  	"updated_at": 1610783813,
   339  	"public_metadata": {},
   340  	"private_metadata": {
   341  		"app_id": 8,
   342  	}
   343  }`