84 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
		
		
			
		
	
	
			84 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
|  | package yushan | |||
|  | 
 | |||
|  | import ( | |||
|  | 	"testing" | |||
|  | 	"time" | |||
|  | ) | |||
|  | 
 | |||
|  | func TestGenerateRequestID(t *testing.T) { | |||
|  | 	service := &YushanService{ | |||
|  | 		config: YushanConfig{ | |||
|  | 			ApiKey: "test_api_key_123", | |||
|  | 		}, | |||
|  | 	} | |||
|  | 	 | |||
|  | 	id1 := service.generateRequestID() | |||
|  | 	 | |||
|  | 	// 等待一小段时间确保时间戳不同 | |||
|  | 	time.Sleep(time.Millisecond) | |||
|  | 	 | |||
|  | 	id2 := service.generateRequestID() | |||
|  | 	 | |||
|  | 	if id1 == "" || id2 == "" { | |||
|  | 		t.Error("请求ID生成失败") | |||
|  | 	} | |||
|  | 	 | |||
|  | 	if id1 == id2 { | |||
|  | 		t.Error("不同时间生成的请求ID应该不同") | |||
|  | 	} | |||
|  | 	 | |||
|  | 	// 验证ID格式 | |||
|  | 	if len(id1) < 20 { // yushan_ + 8位十六进制 + 其他 | |||
|  | 		t.Errorf("请求ID长度不足,实际: %s", id1) | |||
|  | 	} | |||
|  | } | |||
|  | 
 | |||
|  | func TestGenerateRandomString(t *testing.T) { | |||
|  | 	service := &YushanService{} | |||
|  | 	 | |||
|  | 	str1, err := service.GenerateRandomString() | |||
|  | 	if err != nil { | |||
|  | 		t.Fatalf("生成随机字符串失败: %v", err) | |||
|  | 	} | |||
|  | 	 | |||
|  | 	str2, err := service.GenerateRandomString() | |||
|  | 	if err != nil { | |||
|  | 		t.Fatalf("生成随机字符串失败: %v", err) | |||
|  | 	} | |||
|  | 	 | |||
|  | 	if str1 == "" || str2 == "" { | |||
|  | 		t.Error("随机字符串为空") | |||
|  | 	} | |||
|  | 	 | |||
|  | 	if str1 == str2 { | |||
|  | 		t.Error("两次生成的随机字符串应该不同") | |||
|  | 	} | |||
|  | 	 | |||
|  | 	// 验证长度(16字节 = 32位十六进制字符) | |||
|  | 	if len(str1) != 32 || len(str2) != 32 { | |||
|  | 		t.Error("随机字符串长度应该是32位") | |||
|  | 	} | |||
|  | } | |||
|  | 
 | |||
|  | func TestIsJSON(t *testing.T) { | |||
|  | 	testCases := []struct { | |||
|  | 		input    string | |||
|  | 		expected bool | |||
|  | 	}{ | |||
|  | 		{"{}", true}, | |||
|  | 		{"[]", true}, | |||
|  | 		{"{\"key\": \"value\"}", true}, | |||
|  | 		{"[1, 2, 3]", true}, | |||
|  | 		{"invalid json", false}, | |||
|  | 		{"", false}, | |||
|  | 		{"{invalid}", false}, | |||
|  | 	} | |||
|  | 	 | |||
|  | 	for _, tc := range testCases { | |||
|  | 		result := IsJSON(tc.input) | |||
|  | 		if result != tc.expected { | |||
|  | 			t.Errorf("输入: %s, 期望: %v, 实际: %v", tc.input, tc.expected, result) | |||
|  | 		} | |||
|  | 	} | |||
|  | } |