package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gomodule/redigo/redis"
	"github.com/jarcoal/httpmock"
	"github.com/rafaeljusto/redigomock"
	"github.com/stretchr/testify/assert"
	"miads/adslib"
	"miads/adslib/addata"
	"miads/adslib/ads_redis"
	"miads/adslib/redis_data"
	"miads/adslib/utils"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	. "github.com/agiledragon/gomonkey"
)

// func TestAds(t *testing.T) {
// 	router := setupRouter()
//
// 	w := httptest.NewRecorder()
// 	req, _ := http.NewRequest("POST", "/ads?req_source=mh&network_type=9&imei=867252039444772&idfa=&ip=182.37.81.64&ua=Mozilla%2F5.0+%28Linux%3B+Android+8.1.0%3B+MI+8+Build%2FOPM1.171019.026%3B+wv%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Version%2F4.0+Chrome%2F68.0.3440.91+Mobile+Safari%2F537.36&model=MI+8&brand=Xiaomi&android_id=867252039444772&platform=1", nil)
// 	router.ServeHTTP(w, req)
//
// 	assert.Equal(t, 200, w.Code)
// 	assert.Equal(t, "pong", w.Body.String())
// }

func TestDecrypt(t *testing.T) {
	router := setupRouter()

	w := httptest.NewRecorder()
	r := strings.NewReader("")
	req, _ := http.NewRequest("POST", "/ads", r)
	router.ServeHTTP(w, req)

	assert.Equal(t, 200, w.Code)
	assert.Equal(t, "pong", w.Body.String())
}

func TestAdsHandle(t *testing.T) {
	reqBody := "imei=866041034852324&mac=F4:B7:B3:A4:D9:3D&os_version=6.0.1&ip=182.204.243.150&ua=Mozilla%2F5.0+%28Linux%3B+Android+6.0.1%3B+vivo+Y55L+Build%2FMMB29M%3B+wv%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Version%2F4.0+Chrome%2F51.0.2704.81+Mobile+Safari%2F537.36&model=vivo Y55L&brand=vivo&android_id=fa09d9e22ab065b1&platform=1&req_source=kuxin&network_type=9&screen_size=720x1280"
	getAdRspBody := "{\"data\":[{\"tag_id\":\"1.1.10.5\",\"emc_type\":\"pre_play\",\"display_type\":{\"name\":\"video\",\"delay\":0,\"row_count\":0},\"target\":\"mv://Linker?link_url=https%3A%2F%2Fgxb.mmstat.com%2Fgxb.gif%3Ft%3Dhttps%253A%252F%252Fequity.tmall.com%252Ftm%253FagentId%253D346124%2526_bind%253Dtrue%2526mm_unid%253D1_2423553_560501015e6d5757050604556d02545e6f0d51050a0c%26v%3Da5c453178f1c%26di%3D__IDFA__%26dim%3De87d6b2f1ff2d987cd00a924207411e6\",\"skip_time\":0,\"target_addition\":[\"mv://LogHttp?event=VIEW\\u0026url=https%3A%2F%2Fxiaomi.m.cn.miaozhen.com%2Fx%2Fk%3D2174854%26p%3D7asMU%26dx%3D1%26rt%3D2%26pro%3Ds%26ns%3D115.46.124.64%26ni%3Dxiaomi_10215311_A%26v%3D__LOC__%26xa%3D__ADPLATFORM__%26tr%3D__REQUESTID__%26vg%3D__AUTOPLAY__%26nh%3D__AUTOREFRESH__%26mo%3D0%26m0%3D__OPENUDID__%26m0a%3D__DUID__%26m1%3D__ANDROIDID1__%26m1a%3D__ANDROIDID__%26m2%3De87d6b2f1ff2d987cd00a924207411e6%26m4%3D__AAID__%26m5%3D__IDFA__%26m6%3D__MAC1__%26m6a%3D__MAC__%26m11%3D__OAID__%26mn%3D__ANAME__%26o%3D\",\"mv://LogHttp?event=VIEW\\u0026url=http%3A%2F%2Fv2.reachmax.cn%2Fcount%2Frun.php%3Fa%3D9A411698884F75B9394128E8D33E63E9%26ver%3D0%26cpid%3D214878%26pub%3D15%26bc%3DahKlIMbAm3%26l%3D2787725%26cid%3D22057068%26plat%3D2%26s%3D1%26meid%3D4ae081b3798fca7e%26rt%3D1592706305%26t%3Ds\",\"mv://LogHttp?event=VIEW\\u0026url=http%3A%2F%2Fm.track.ad.xiaomi.com%2Ftask%2Fimp%2F47e83263d4%2Fe1bef0f1aa%2C0a__MAC__%2C0be87d6b2f1ff2d987cd00a924207411e6%2C0c__OAID__%2C0d10215311%2C0e__ANDROIDVERSION__%2C0f__PLATFORM__%2C0k1.1.10.5%2C0h\",\"mv://LogHttp?event=CLICK\\u0026url=https%3A%2F%2Fxiaomi.m.cn.miaozhen.com%2Fr%2Fk%3D2174854%26p%3D7asMU%26dx%3D1%26rt%3D2%26pro%3Ds%26ns%3D115.46.124.64%26ni%3Dxiaomi_10215311%26v%3D__LOC__%26xa%3D__ADPLATFORM__%26tr%3D__REQUESTID__%26mo%3D0%26m0%3D__OPENUDID__%26m0a%3D__DUID__%26m1%3D__ANDROIDID1__%26m1a%3D__ANDROIDID__%26m2%3De87d6b2f1ff2d987cd00a924207411e6%26m4%3D__AAID__%26m5%3D__IDFA__%26m6%3D__MAC1__%26m6a%3D__MAC__%26m11%3D__OAID__%26mn%3D__ANAME__%26o%3D\",\"mv://LogHttp?event=CLICK\\u0026url=http%3A%2F%2Fv2.reachmax.cn%2Fclick%2Frun.php%3Fa%3D9A411698884F75B9394128E8D33E63E9%26ver%3D0%26cpid%3D214878%26pub%3D15%26bc%3DahKlIMbAm3%26l%3D2787725%26cid%3D22057068%26plat%3D2%26s%3D1%26meid%3D4ae081b3798fca7e%26rt%3D1592706305\",\"mv://LogHttp?event=VIEW\\u0026url=http%3A%2F%2Fapi.ad.xiaomi.com%2Fiqiyi%2FuploadLogAdSDK%3Fvalue%3DeyJCIjpbeyJCIjp7Il9hY3Rpb25fIjoiVklFVyIsIl9jYXRlZ29yeV8iOiJhZCIsImUiOiJWSUVXIiwiZXgiOiJobWJfY2tNZDVpM19ZQ0JSQWxVZ3BEU0F5VXdVNnc4QjJ2WG1vSkZSOF9yYmlOdndZOTJZb1FibWFSaDJJQ2FqcWp3WlZnaEtWTnhGZElPZjVTXzdZODh2aF9SVW11eXl4dVMtNGxsVmYzVThuZ1NhdGNBRzI2dUlCSF9qM1E2RUNqOFFodnhmQTFjNHR6Q1k5WGlDdUlBbDljTmF5cFZsUW1DeUJwelZ4UWZWZlNScXBWVTZvOUhNazV1LXlGY1R0SVBLeERZcTNu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TBfZXgzcVdDSlJzUUVqVVR5WUNlMTNfWXlTZlVYM3lVMEJXeXp2ZnNoT01EaTBaRVFDRjcwa3M4OVVlSmdlN0t3Ul9DTThyS0F1bHhLMjhwcUFhS1cwb09lS1FrVjMxRElBIiwidCI6IjE1OTI3MDYzMDUiLCJ2IjoiIn0sIkgiOnsiZXZlbnRUaW1lIjoiMTU5MjcwNjMwNSIsImtleSI6InZpZGVvX2FkbG9nIiwicGsiOiJjb20ubWl1aS52aWRlbyIsInJldHJ5Q250IjowLCJzaWQiOiIiLCJzbiI6IiJ9fV0sIkgiOnsiYWFpZCI6IiIsImFuZHJvaWQiOiIiLCJibiI6IiIsImN2IjoiIiwiZGV2aWNlIjoiIiwiaW1laSI6ImU4N2Q2YjJmMWZmMmQ5ODdjZDAwYTkyNDIwNzQxMWU2IiwibGFuZyI6IiIsIm1hYyI6IiIsIm1pIjoiIiwibWl1aSI6IiIsIm1vZGVsIjoiIiwibiI6IiIsInByb2R1Y3QiOiIiLCJyZWdpb24iOiIiLCJzZW5kZXIiOiIiLCJzdCI6IjE1OTI3MDYzMDUiLCJ1c2VyaWQiOjB9fQ%3D%3D%26ts%3D1592706305%26nonce%3D8006cab6290b646914aebb2e0d5c8c02%26sign%3Da324d23a903ff7a1f4b01808e18a8afe\"],\"target_addition1\":null,\"title\":\"\",\"duration\":15,\"image_url\":\"\",\"video_url\":\"https://video.market.xiaomi.com/download/AdCenter/01d78487ca2a1143dbe27a29c8f0855966e42bd8b/AdCenter01d78487ca2a1143dbe27a29c8f0855966e42bd8b.mp4\",\"id\":\"10215311\",\"detail_url\":\"\",\"settings\":{\"click_type\":\"0\",\"show_close_at\":-1,\"hide_close_at\":-1,\"log_time\":\"\",\"click_ratio\":0,\"video_finish_ratio\":0,\"video_timer_ratio\":0},\"proportion\":\"1040:467\",\"load_ext\":\"\",\"n_urls\":null,\"buttonName\":\"查看详情\",\"is_download\":\"0\"}],\"eid\":\"ab60:1,ab59:99,ab54:02,ab58:99,ab41:1,ab49:2,ab17:1,ab29:10,ab_feed2:1,ab_feed1:0,ab31:0||\",\"msg\":\"OK\",\"result\":1}"
	getOneAdRsp := "{u'show_kpi': 60000, u'region_flag': 0, u'click_url': u'', 'rad': 16, u'target_url': u'https://api-luke.mama.cn/click?source=3&luke_t=256c65f3cac54999&luke_p=1938757_5460&luke_device=__DEVICE__&luke_mobileid=__MOBILEID__&luke_dno=&luke_d1=&luke_d1a=&luke_d2=&uid=&luke_uid=__UID__&luke_dt=d50c1e73a36ac1ef3b667e71051c17b1&luke_dest=http%3A%2F%2Fclickc.admaster.com.cn%2Fc%2Fa141396%2Cb4111860%2Cc2233%2Ci0%2Cm101%2C8a2%2C8b2%2C0a%2C0c%2Cz%2Cf__IP__%2Ch%2Cuhttps%253A%252F%252Fccc-x.jd.com%252Fdsp%252Fcl%253Fposid%253D1999%2526v%253D707%2526union_id%253D1000023384%2526pid%253D2450%2526tagid%253D123504%2526didmd5%253D%2526idfamd5%253D%2526did%253D__IMEIIMEI__%2526idfa%253D__IDFAIDFA__%2526to%253Dhttps%25253A%25252F%25252Fh5.m.jd.com%25252FbabelDiy%25252FZeus%25252F2kmm2cwm3PyTsE56ouW62ArGWLba%25252Findex.html%25253Fad_od%25253D1%252526babelChannel%25253Dttt1', u'line_type': 1, u'imei_replace_flag': 0, u'city': u'', u'order_type': 0, u'title': u'mm_1938757', u'region_info': u'', u'channel': u'kuxin,zhiku', u'province': u'', u'order_id': 8737, u'click_kpi': 60000, u'no_city': u'', u'no_province': u'', u'begin_time': 1592668800, u'show_url': u'', u'js_order_id': 84920, u'level': 100, u'new_region_flag': u'0', u'end_time': 1592748000}"

	err := ads_redis.Setup()
	assert.Nil(t, err)

	conn := redigomock.NewConn()
	ads_redis.RedisConn = &redis.Pool{
		// Return the same connection mock for each Get() call.
		Dial:    func() (redis.Conn, error) { return conn, nil },
		MaxIdle: 10,
	}

	// mock GetOneAds
	patches := ApplyFunc(addata.GetOneAds, func(dsp *utils.DspParam, orderType int, fixFlag int) (*redis_data.AdOrderInfo, error) {
		rspJson := getOneAdRsp
		rspJson = strings.ReplaceAll(rspJson, "u'", "'")
		rspJson = strings.ReplaceAll(rspJson, "'", "\"")
		//rspJson = strings.ReplaceAll(rspJson,"\\", "")

		order := redis_data.AdOrderInfo{}
		err := json.Unmarshal([]byte(rspJson), &order)
		if err != nil {
			return nil, err
		}

		return &order, nil
	})
	defer patches.Reset()

	conn.Command("GET", "time_all_count_8744_2").Expect(int64(1587238))
	conn.Command("GET", "time_all_count_8744_1320").Expect(int64(42021))

	conn.Command("SISMEMBER", "arsi", "zhiku").Expect([]byte("true"))
	conn.Command("SISMEMBER", "arsi", "kuxin").Expect([]byte("true"))
	conn.Command("SISMEMBER", "arsi", "kuxin2").Expect([]byte("true"))
	conn.Command("SISMEMBER", "arsi", "kuxin02").Expect([]byte("true"))
	conn.Command("SISMEMBER", "ads_black_ip", "183.210.200.149").Expect([]byte("false"))
	conn.Command("SISMEMBER", "ads_black_ip", "223.101.216.110").Expect([]byte("false"))
	conn.Command("SISMEMBER", "ads_black_ip", "39.171.135.92").Expect([]byte("false"))
	conn.Command("SISMEMBER", "ads_black_ip", "223.146.38.234").Expect([]byte("false"))
	conn.Command("SISMEMBER", "ads_black_ip", "223.104.16.159").Expect([]byte("false"))
	conn.Command("SISMEMBER", "ads_black_ip", "203.93.164.105").Expect([]byte("false"))
	conn.Command("SISMEMBER", "ads_black_device_1e", "1e0c983e7e0cf28158e04010edb74497").Expect([]byte("false"))
	conn.Command("SISMEMBER", "ads_black_device_9a", "9a9b3bfd264dcace07ee89154bc46601").Expect([]byte("false"))
	conn.Command("SISMEMBER", "ads_black_device_dc", "dcd7e94f8eecb58b46195f1b74329bbb").Expect([]byte("false"))
	conn.Command("SISMEMBER", "ads_black_device_14", "148db5a003bc49053c02c408f3db9dda").Expect([]byte("false"))
	conn.GenericCommand("SISMEMBER").Handle(redigomock.ResponseHandler(func(args []interface{}) (interface{}, error) {
		key := args[0].(string)
		//v := args[1].(string)
		if strings.HasPrefix(key, "ads_black_device_") || key == "ads_black_ip" {
			return interface{}([]byte("false")), nil
		}
		return nil, errors.New(fmt.Sprintf("no such command: %s", key))
	}))

	conn.Command("GET", "ads_city_佳木斯市").Expect(int64(1156230800))
	conn.Command("GET", "ads_city_葫芦岛市").Expect(int64(1156211400))
	conn.Command("GET", "ads_city_绵阳市").Expect(int64(1156510700))
	conn.Command("GET", "ads_city_鹤壁市").Expect(int64(1156410600))
	conn.Command("GET", "ads_city_南平市").Expect(int64(1156350700))
	conn.Command("GET", "ads_city_宿州市").Expect(int64(1156341300))
	conn.Command("GET", "ads_city_牡丹江市").Expect(int64(1156231000))
	conn.Command("GET", "ads_city_哈尔滨市").Expect(int64(1156230100))
	conn.Command("GET", "ads_city_泉州市").Expect(int64(1156350500))
	conn.Command("GET", "ads_city_上海市").Expect(int64(1156310000))
	conn.Command("GET", "ads_city_拉萨市").Expect(int64(1156540100))
	conn.Command("GET", "ads_city_常州市").Expect(int64(1156320400))
	conn.Command("GET", "ads_city_铁岭市").Expect(int64(1156211200))
	conn.Command("GET", "ads_city_武汉市").Expect(int64(1156420100))
	conn.Command("GET", "ads_city_绍兴市").Expect(int64(1156330600))
	conn.Command("GET", "ads_city_衡阳市").Expect(int64(1156430400))
	conn.Command("GET", "ads_city_保定市").Expect(int64(1156130600))
	conn.Command("GET", "ads_city_银川市").Expect(int64(1156640100))
	conn.Command("GET", "ads_city_长春市").Expect(int64(1156220100))
	conn.Command("GET", "ads_city_漳州市").Expect(int64(1156350600))
	conn.Command("GET", "ads_city_本溪市").Expect(int64(1156210500))
	conn.Command("GET", "ads_city_苏州市").Expect(int64(1156320500))
	conn.Command("GET", "rsfreq_zhiku").Expect("[{\"freq_time\": 60, \"end_hour\": 23, \"begin_hour\": 0}]")
	conn.Command("GET", "acfv2_{kuxin02}_{ads_click}").Expect("{\"channel_flag\": 1, \"weigth\": 100}")
	conn.Command("GET", "acfv2_kuxin_ads_click").Expect("{\"channel_flag\": 1, \"weigth\": 100}")
	conn.Command("GET", "acfv2_zhiku_ads_click").Expect("{\"channel_flag\": 1, \"weigth\": 100}")
	conn.Command("GET", "acfv2_kuxin_ads_req").Expect("{\"channel_flag\": 1, \"weigth\": 100}")
	conn.Command("GET", "acfv2_kuxin_ads_mix").Expect("{\"channel_flag\": 1, \"weigth\": 100}")
	conn.Command("GET", "acfv2_zhiku_ads_req").Expect("{\"channel_flag\": 1, \"weigth\": 100}")
	conn.Command("GET", "acfv2_zhiku_ads_mix").Expect("{\"channel_flag\": 1, \"weigth\": 100}")
	conn.Command("GET", "adsv2_xiaomi_0").Expect(int64(2735))
	conn.Command("GET", "adsv3_xiaomi_VIEW_0").Expect(int64(0))
	conn.Command("GET", "adsv3_xiaomi_VIDEO_TIMER_0").Expect(int64(215))
	conn.Command("GET", "adsv3_xiaomi_CLICK_0").Expect(int64(82))
	conn.Command("GET", "adsv3_xiaomi_VIDEO_FINISH_0").Expect(int64(2654))
	conn.Command("GET", "dim2_9a9b3bfd264dcace07ee89154bc46601_'223.146.38.234'").Expect([]byte("false"))
	conn.Command("GET", "dim2_dcd7e94f8eecb58b46195f1b74329bbb_'183.199.36.10'").Expect([]byte("false"))
	conn.Command("GET", "dim2_72710e3df592f07f6dbcc04b747f3653_'223.91.87.241'").Expect(int64(time.Now().Unix()))
	conn.Command("GET", "dim2_148b42358abcfcf55f99bee149b7689d_'203.93.164.105'").Expect(int64(time.Now().Unix()))
	conn.Command("GET", "rsfreq_kuxin").Expect("[{\"freq_time\": 60, \"end_hour\": 23, \"begin_hour\": 0}]")
	conn.Command("GET", "rsfreq_kuxin02").Expect("[{\"freq_time\": 60, \"end_hour\": 23, \"begin_hour\": 0}]")
	conn.Command("GET", "adv_script_xiaomi").Expect(int64(1))
	conn.GenericCommand("GET").Handle(redigomock.ResponseHandler(func(args []interface{}) (interface{}, error) {
		key := args[0].(string)
		if strings.HasPrefix(key, "adip_") {
			return interface{}(time.Now().Unix() - 1000), nil
		} else if strings.HasPrefix(key, "time_8737_") {
			return interface{}(int64(1877)), nil
		} else if key == "order_kpi_8744_2020620_show_kpi" {
			return interface{}(int64(1400451)), nil
		} else if strings.HasPrefix(key, "order_kpi_8744_2020620_") {
			return interface{}(int64(201)), nil
		} else if strings.HasPrefix(key, "dim2_") {
			return interface{}([]byte("false")), nil
		}
		return nil, errors.New(fmt.Sprintf("no such command: %s", key))
	}))
	conn.Command("GET", "adur_182.137.55.122_20200621_2_v4").Expect("{\"imei\": \"e87d6b2f1ff2d987cd00a924207411e6\", \"origin_imei\": \"99001215020428\", \"ua\": \"Mozilla/5.0 (Linux; Android 8.1; MI 8 SE Build/OPM1.171019.019; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/044303 Mobile Safari/537.36 V1_AND_SQ_7.9.7_996_YYB_D QQ/7.9.7.3925 NetType/4G WebP/0.3.0 Pixel/1080 StatusBarHeight/110\"}")
	conn.Command("GET", "adur_110.81.61.229_20200620_2_v4").Expect("{\"imei\": \"31236dcc65434d3ddbbe443f958583b8\", \"origin_imei\": \"863818031803555\", \"ua\": \"Mozilla/5.0 (Linux; Android 6.0.1; Redmi 4 Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 Mobile Safari/537.36,11,368\"}")
	conn.Command("GET", "adur_180.167.174.21_20200620_2_v4").Expect("{\"imei\": \"360319c7973a6d81294f3bcb46a619e7\", \"origin_imei\": \"99000712694168\", \"ua\": \"Mozilla/5.0 (Linux; Android 7.1.2; Redmi 5 Build/N2G47H; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044607 Mobile Safari/537.36 V1_AND_SQ_7.7.0_882_YYB_D QQ/7.7.0.3640 NetType/4G WebP/0.3.0 Pixel/720\"}")
	conn.Command("GET", "adur_42.226.86.138_20200621_2_v4").Expect("{\"imei\": \"d6ed8ef5f9f4874d6df71e78d8b2c83a\", \"origin_imei\": \"865394039233268\", \"ua\": \"mozilla/5.0 (linux; android 7.1.2; redmi note 5a build/n2g47h; wv) applewebkit/537.36 (khtml, like gecko) version/4.0 chrome/66.0.3359.126 mqqbrowser/6.2 tbs/044607 mobile safari/537.36 v1_and_sq_7.9.9_1010_yyb_d qq/7.9.9.3965 nettype/4g webp/0.3.0 pixel/720 statusbarheight/50\"}")
	conn.Command("GET", "adur_182.204.243.150_20200621_2_v4").Expect("{\"imei\": \"7d4204760148ef2aec19da18a7cb058f\", \"origin_imei\": \"868453040472492\", \"ua\": \" Mozilla/5.0 (Linux; Android 9; MI 8 Build/PKQ1.180729.001; wv) AppleWebKit/537.36 (KHTML like Gecko) Version/4.0 Chrome/72.0.3626.121 Mobile Safari/537.36\"}")
	conn.Command("GET", "ads_ios_20200620_110.81.61.229").Expect("{\"imei\": \"0AD46490-A5DF-4BBA-B81B-F3063576E64E\", \"ua\": \"Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15G77\"}")
	conn.Command("GET", "ads_ios_20200620_223.104.16.159").Expect("{\"imei\": \"FC7F4191-F9A9-4A3D-A485-6A3477545AE7\", \"ua\": \"Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148\"}")
	conn.Command("GET", "ads_ios_20200621_183.253.160.105").Expect("{\"imei\": \"6D746B9C-1D6F-4F38-9500-F3319C94906D\", \"ua\": \"Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15F79\"}")
	conn.Command("GET", "ads_ios_20200621_182.137.55.122").Expect("nil")
	conn.Command("GET", "ads_ios_20200620_180.108.237.220").Expect("{\"imei\": \"62DFC333-4F61-4FC5-AFF1-9F870210D05F\", \"ua\": \"Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML like Gecko) Mobile/15E148\"}")
	conn.GenericCommand("INCR").Handle(redigomock.ResponseHandler(func(args []interface{}) (interface{}, error) {
		key := args[0].(string)
		if strings.HasPrefix(key, "order_kpi_8745_2020620_") {
			return interface{}(123), nil
		} else if strings.HasPrefix(key, "order_kpi_8744_2020620_") {
			return interface{}(123), nil
		} else if strings.HasPrefix(key, "order_kpi_8737_2020621_") {
			return interface{}(123), nil
		} else if strings.HasPrefix(key, "time_8745_") {
			return interface{}(1913), nil
		}
		return nil, errors.New(fmt.Sprintf("no such incr command: %s", key))
	}))
	conn.Command("GET", "time_all_count_8737_2").Expect(int64(1587238))
	conn.Command("GET", "time_all_count_8737_1320").Expect(int64(42021))
	conn.Command("GET", "order_kpi_8737_2020621_show_kpi").Expect(int64(16729))
	if err != nil {
		fmt.Printf("setup redis failed: %s\n", err)
		return
	}

	httpmock.Activate()
	defer httpmock.DeactivateAndReset()
	httpmock.RegisterResponder("GET", "https://m.video.xiaomi.com/api/a3/otv_emc",
		func(req *http.Request) (*http.Response, error) {
			body := getAdRspBody
			return httpmock.NewStringResponse(200, body), nil
		},
	)

	adslib.GetConf()

	router := setupRouter()

	w := httptest.NewRecorder()
	r := strings.NewReader(reqBody)
	req, _ := http.NewRequest("POST", "/ads", r)
	router.ServeHTTP(w, req)

	assert.Equal(t, "pong", w.Body.String())
	assert.Equal(t, 200, w.Code)
}
