github.com/fastwego/offiaccount@v1.0.1/client_test.go (about)

     1  // Copyright 2020 FastWeGo
     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  
    15  package offiaccount
    16  
    17  import (
    18  	"fmt"
    19  	"net/http"
    20  	"net/http/httptest"
    21  	"testing"
    22  )
    23  
    24  func TestClient_getAccessToken(t *testing.T) {
    25  
    26  	var MockOffiAccount = New(Config{
    27  		Appid:  "TestClient_getAccessToken",
    28  		Secret: "SECRET",
    29  	})
    30  
    31  	// Mock Server
    32  	var MockSvrHandler = http.NewServeMux()
    33  	var MockSvr = httptest.NewServer(MockSvrHandler)
    34  	WXServerUrl = MockSvr.URL // 拦截发往微信服务器的请求
    35  
    36  	mockResp := map[string][]byte{
    37  		"case1": []byte(`{"access_token":"ACCESS_TOKEN","expires_in":3}`),
    38  		"case2": []byte(`{"errcode":40013,"errmsg":"invalid appid"}`),
    39  	}
    40  	var resp []byte
    41  
    42  	// Mock access token
    43  	MockSvrHandler.HandleFunc("/cgi-bin/token", func(w http.ResponseWriter, r *http.Request) {
    44  		_, _ = w.Write(resp)
    45  	})
    46  	client := &Client{
    47  		Ctx: MockOffiAccount,
    48  	}
    49  
    50  	tests := []struct {
    51  		name            string
    52  		wantAccessToken string
    53  		wantErr         bool
    54  	}{
    55  		{name: "case1", wantAccessToken: "ACCESS_TOKEN", wantErr: false},
    56  		{name: "case2", wantAccessToken: "", wantErr: true},
    57  	}
    58  	for _, tt := range tests {
    59  		t.Run(tt.name, func(t *testing.T) {
    60  			client.Ctx.AccessToken.Cache.Delete(client.Ctx.Config.Appid)
    61  			resp = mockResp[tt.name]
    62  			gotAccessToken, err := GetAccessToken(client.Ctx)
    63  			fmt.Println(gotAccessToken, err)
    64  			if (err != nil) != tt.wantErr {
    65  				t.Errorf("GetAccessToken() error = %v, wantErr %v", err, tt.wantErr)
    66  				return
    67  			}
    68  			if gotAccessToken != tt.wantAccessToken {
    69  				t.Errorf("GetAccessToken() gotAccessToken = %v, want %v", gotAccessToken, tt.wantAccessToken)
    70  			}
    71  		})
    72  	}
    73  }