gitee.com/larksuite/oapi-sdk-go/v3@v3.0.3/card/card_test.go (about)

     1  /*
     2   * MIT License
     3   *
     4   * Copyright (c) 2022 Lark Technologies Pte. Ltd.
     5   *
     6   * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
     7   *
     8   * The above copyright notice and this permission notice, shall be included in all copies or substantial portions of the Software.
     9   *
    10   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    11   */
    12  
    13  package larkcard
    14  
    15  import (
    16  	"context"
    17  	"encoding/json"
    18  	"errors"
    19  	"fmt"
    20  	"net/http"
    21  	"testing"
    22  
    23  	"gitee.com/larksuite/oapi-sdk-go/v3/core"
    24  	"gitee.com/larksuite/oapi-sdk-go/v3/event"
    25  )
    26  
    27  func TestVerifyUrlOk(t *testing.T) {
    28  	// 创建card处理器
    29  	cardHandler := NewCardActionHandler("12", "", func(ctx context.Context, cardAction *CardAction) (interface{}, error) {
    30  		return nil, nil
    31  	})
    32  
    33  	//plainEventJsonStr := "{\"open_id\":\"ou_sdfimx9948345\",\"user_id\":\"eu_sd923r0sdf5\",\"open_message_id\":\"om_abcdefg1234567890\",\"tenant_key\":\"d32004232\",\"token\":\"12\",\"timezone\":\"\",\"action\":{\"value\":{\"tag\":\"button\",\"value\":\"sdfsfd\"},\"tag\":\"button\",\"option\":\"\",\"timezone\":\"\"},\"challenge\":\"121212\",\"type\":\"url_verification\"}"
    34  	cardAction := mockCardAction()
    35  
    36  	resp, err := cardHandler.AuthByChallenge(context.Background(), cardAction)
    37  	if err != nil {
    38  		t.Errorf("verfiy url failed ,%v", err)
    39  	}
    40  
    41  	if resp.Body == nil {
    42  		t.Errorf("verfiy url failed")
    43  	}
    44  
    45  }
    46  
    47  func TestVerifyUrlFailed(t *testing.T) {
    48  	// 创建card处理器
    49  	cardHandler := NewCardActionHandler("121", "", func(ctx context.Context, cardAction *CardAction) (interface{}, error) {
    50  		return nil, nil
    51  	})
    52  
    53  	cardAction := mockCardAction()
    54  	_, err := cardHandler.AuthByChallenge(context.Background(), cardAction)
    55  	if err == nil {
    56  		t.Errorf("verfiy url failed ,%v", err)
    57  		return
    58  	}
    59  
    60  }
    61  
    62  func mockEventReq(token string) *larkevent.EventReq {
    63  	value := map[string]interface{}{}
    64  	value["value"] = "sdfsfd"
    65  	value["tag"] = "button"
    66  
    67  	cardAction := &CardAction{
    68  		OpenID:        "ou_sdfimx9948345",
    69  		UserID:        "eu_sd923r0sdf5",
    70  		OpenMessageID: "om_abcdefg1234567890",
    71  		TenantKey:     "d32004232",
    72  		Token:         token,
    73  		Action: &struct {
    74  			Value    map[string]interface{} `json:"value"`
    75  			Tag      string                 `json:"tag"`
    76  			Option   string                 `json:"option"`
    77  			Timezone string                 `json:"timezone"`
    78  		}{
    79  			Value: value,
    80  			Tag:   "button",
    81  		},
    82  	}
    83  
    84  	cardActionBody := &CardActionBody{
    85  		CardAction: cardAction,
    86  		Challenge:  "121212",
    87  		Type:       "",
    88  	}
    89  
    90  	body, _ := json.Marshal(cardActionBody)
    91  	var timestamp = "timestamp"
    92  	var nonce = "nonce"
    93  
    94  	sign := Signature(timestamp, nonce, token, string(body))
    95  
    96  	header := http.Header{}
    97  	header.Set(larkevent.EventRequestTimestamp, timestamp)
    98  	header.Set(larkevent.EventRequestNonce, nonce)
    99  	header.Set(larkevent.EventSignature, sign)
   100  	req := &larkevent.EventReq{
   101  		Header: header,
   102  		Body:   body,
   103  	}
   104  
   105  	return req
   106  }
   107  
   108  func TestVerifySignOk(t *testing.T) {
   109  	// 创建card处理器
   110  	cardHandler := NewCardActionHandler("121", "", func(ctx context.Context, cardAction *CardAction) (interface{}, error) {
   111  		return nil, nil
   112  	})
   113  
   114  	config := &larkcore.Config{}
   115  	larkcore.NewLogger(config)
   116  	cardHandler.Config = config
   117  
   118  	req := mockEventReq("121")
   119  	err := cardHandler.VerifySign(context.Background(), req)
   120  	if err != nil {
   121  		t.Errorf("verfiy url failed ,%v", err)
   122  		return
   123  	}
   124  }
   125  
   126  func TestVerifySignFailed(t *testing.T) {
   127  	// 创建card处理器
   128  	cardHandler := NewCardActionHandler("121", "", func(ctx context.Context, cardAction *CardAction) (interface{}, error) {
   129  		return nil, nil
   130  	})
   131  
   132  	config := &larkcore.Config{}
   133  	larkcore.NewLogger(config)
   134  	cardHandler.Config = config
   135  
   136  	req := mockEventReq("12")
   137  	err := cardHandler.VerifySign(context.Background(), req)
   138  	if err == nil {
   139  		t.Errorf("verfiy url failed ,%v", err)
   140  		return
   141  	}
   142  }
   143  
   144  func TestDoHandleResultNilOk(t *testing.T) {
   145  	// 创建card处理器
   146  	cardHandler := NewCardActionHandler("12", "", func(ctx context.Context, cardAction *CardAction) (interface{}, error) {
   147  		return nil, nil
   148  	})
   149  
   150  	cardAction := mockCardAction()
   151  	resp, err := cardHandler.DoHandle(context.Background(), cardAction)
   152  	if err != nil {
   153  		t.Errorf("verfiy url failed ,%v", err)
   154  		return
   155  	}
   156  
   157  	fmt.Println(resp.StatusCode)
   158  	fmt.Println(larkcore.Prettify(resp.Header))
   159  	fmt.Println(string(resp.Body))
   160  }
   161  
   162  func TestDoHandleResultError(t *testing.T) {
   163  	// 创建card处理器
   164  	cardHandler := NewCardActionHandler("121", "", func(ctx context.Context, cardAction *CardAction) (interface{}, error) {
   165  		return nil, errors.New("im an error ")
   166  	})
   167  
   168  	cardAction := &CardAction{}
   169  	_, err := cardHandler.DoHandle(context.Background(), cardAction)
   170  	if err == nil {
   171  		t.Errorf("handler error  ,%v", err)
   172  		return
   173  	}
   174  
   175  }
   176  
   177  func TestDoHandleResultCustomRespOk(t *testing.T) {
   178  	// 创建card处理器
   179  	cardHandler := NewCardActionHandler("12", "", func(ctx context.Context, cardAction *CardAction) (interface{}, error) {
   180  		body := make(map[string]interface{})
   181  		body["content"] = "hello"
   182  
   183  		i18n := make(map[string]string)
   184  		i18n["zh_cn"] = "你好"
   185  		i18n["en_us"] = "hello"
   186  		i18n["ja_jp"] = "こんにちは"
   187  		body["i18n"] = i18n
   188  
   189  		resp := CustomResp{
   190  			StatusCode: 400,
   191  			Body:       body,
   192  		}
   193  
   194  		return &resp, nil
   195  	})
   196  
   197  	cardAction := mockCardAction()
   198  	resp, err := cardHandler.DoHandle(context.Background(), cardAction)
   199  	if err != nil {
   200  		t.Errorf("verfiy url failed ,%v", err)
   201  		return
   202  	}
   203  
   204  	fmt.Println(resp.StatusCode)
   205  	fmt.Println(larkcore.Prettify(resp.Header))
   206  	fmt.Println(string(resp.Body))
   207  }
   208  
   209  func mockCardAction() *CardAction {
   210  	// 构建card,并返回
   211  	value := map[string]interface{}{}
   212  	value["value"] = "1111sdfsfd"
   213  	value["tag"] = "b11111utton"
   214  	cardAction := &CardAction{
   215  		Type:          string(larkevent.ReqTypeChallenge),
   216  		Token:         "12",
   217  		OpenID:        "ou_sdfimx9948345",
   218  		UserID:        "eu_sd923r0sdf5",
   219  		OpenMessageID: "om_abcdefg1234567890",
   220  		TenantKey:     "d32004232",
   221  		Action: &struct {
   222  			Value    map[string]interface{} `json:"value"`
   223  			Tag      string                 `json:"tag"`
   224  			Option   string                 `json:"option"`
   225  			Timezone string                 `json:"timezone"`
   226  		}{
   227  			Value: value,
   228  			Tag:   "button",
   229  		},
   230  	}
   231  
   232  	return cardAction
   233  }
   234  func TestDoHandleResultCardOk(t *testing.T) {
   235  	// 创建card处理器
   236  	cardHandler := NewCardActionHandler("12", "", func(ctx context.Context, cardAction *CardAction) (interface{}, error) {
   237  		// 构建card,并返回
   238  		value := map[string]interface{}{}
   239  		value["value"] = "1111sdfsfd"
   240  		value["tag"] = "b11111utton"
   241  
   242  		cardActionResult := &CardAction{
   243  			OpenID:        "ou_sdfimx9948345",
   244  			UserID:        "eu_sd923r0sdf5",
   245  			OpenMessageID: "om_abcdefg1234567890",
   246  			TenantKey:     "d32004232",
   247  			Action: &struct {
   248  				Value    map[string]interface{} `json:"value"`
   249  				Tag      string                 `json:"tag"`
   250  				Option   string                 `json:"option"`
   251  				Timezone string                 `json:"timezone"`
   252  			}{
   253  				Value: value,
   254  				Tag:   "button",
   255  			},
   256  		}
   257  		return cardActionResult, nil
   258  	})
   259  
   260  	resp, err := cardHandler.DoHandle(context.Background(), mockCardAction())
   261  	if err != nil {
   262  		t.Errorf("verfiy url failed ,%v", err)
   263  		return
   264  	}
   265  
   266  	fmt.Println(resp.StatusCode)
   267  	fmt.Println(larkcore.Prettify(resp.Header))
   268  	fmt.Println(string(resp.Body))
   269  }