package main

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"testing"
)

//get accesstoken from wechat server or local cache file
func TestAccessToken(t *testing.T) {
	SetupConfig()
	token, err := GetAccessToken()
	if err != nil {
		t.Error("Cannot get AccessToken From Tencent Wechat Server")
	}

	AssertEqual(t, token, WechatAccessToken.AccessToken, "Global accesstoken is not uptodate")
}

//save token to a file and read it back
func TestTokenStorage(t *testing.T) {
	var s AuthToken
	s.AccessToken = "s0wf65p-KMzvYtH8qPu2qSX_EXLE2NaBgFHl7MZwedc7Kv_hdO0FG1QeUmBYJAGmQqJinPwFr67MRZwJee4rDnGVwhbuIfKs29N4ZJSXFP8fbAheuas08UuRe13UsdCtWSMcAFAGCW"
	s.ExpireIn = 7200
	msg, _ := json.Marshal(s)
	file, _ := ioutil.TempFile(os.TempDir(), "wechat_token_")
	defer os.Remove(file.Name())
	writeTokenToFile([]byte(msg), file.Name())
	token, _ := readTokenFromFile(file.Name())
	AssertEqual(t, s, token, "read token should be correct")
}

//read config, make sure its not empty
func TestReadConfig(t *testing.T) {
	SetupConfig()
	if APIConfig.AppSecret == "" {
		t.Error("AppSecret not available")
	}
	if APIConfig.Appid == "" {
		t.Error("AppId not available")
	}
	if APIConfig.AuthTokenSaveTo == "" {
		t.Error("where to save accesstoken is unknown")
	}
	if APIConfig.EncodingAESKey == "" {
		t.Error("unknown AesEncryptionKey")
	}
	if APIConfig.Token == "" {
		t.Error("hidden shared secret token is empty")
	}
}
