github.com/fastwego/offiaccount@v1.0.1/test/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 test 模拟微信服务器 测试
    16  package test
    17  
    18  import (
    19  	"net/http"
    20  	"net/http/httptest"
    21  	"sync"
    22  
    23  	"github.com/fastwego/offiaccount"
    24  )
    25  
    26  var MockOffiAccount *offiaccount.OffiAccount
    27  var MockSvr *httptest.Server
    28  var MockSvrHandler *http.ServeMux
    29  var onceSetup sync.Once
    30  
    31  // 初始化测试环境
    32  func Setup() {
    33  	onceSetup.Do(func() {
    34  
    35  		MockOffiAccount = offiaccount.New(offiaccount.Config{
    36  			Appid:          "APPID",
    37  			Secret:         "SECRET",
    38  			Token:          "TOKEN",
    39  			EncodingAESKey: "EncodingAESKey",
    40  		})
    41  
    42  		// Mock Server
    43  		MockSvrHandler = http.NewServeMux()
    44  		MockSvr = httptest.NewServer(MockSvrHandler)
    45  		offiaccount.WXServerUrl = MockSvr.URL // 拦截发往微信服务器的请求
    46  
    47  		// Mock access token
    48  		MockSvrHandler.HandleFunc("/cgi-bin/token", func(w http.ResponseWriter, r *http.Request) {
    49  			_, _ = w.Write([]byte(`{"access_token":"ACCESS_TOKEN","expires_in":7200}`))
    50  		})
    51  	})
    52  }