context_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package tests
  2. import (
  3. "fmt"
  4. "shudao-chat-go/utils"
  5. "testing"
  6. "github.com/beego/beego/v2/server/web/context"
  7. )
  8. // TestContextDataStorage 测试context数据存储和获取
  9. func TestContextDataStorage(t *testing.T) {
  10. // 创建一个模拟的 BeegoInput
  11. ctx := &context.Context{
  12. Input: context.NewInput(),
  13. }
  14. // 创建测试用户信息
  15. testUserInfo := &utils.TokenUserInfo{
  16. AccountID: "test123",
  17. ID: 12345,
  18. Name: "测试用户",
  19. UserCode: "T001",
  20. ContactNumber: "13800138000",
  21. TokenType: "access",
  22. Exp: 1234567890,
  23. Iat: 1234567800,
  24. }
  25. fmt.Println("\n========== Context存储测试 ==========")
  26. fmt.Printf("原始用户信息: %+v\n", testUserInfo)
  27. fmt.Printf("原始指针地址: %p\n\n", testUserInfo)
  28. // 存储到context
  29. ctx.Input.SetData("userInfo", testUserInfo)
  30. fmt.Println("✅ 已存储到context")
  31. // 立即从context获取
  32. storedData := ctx.Input.GetData("userInfo")
  33. fmt.Printf("\n从context获取的数据:\n")
  34. fmt.Printf(" 类型: %T\n", storedData)
  35. fmt.Printf(" 值: %+v\n\n", storedData)
  36. // 使用 GetUserInfoFromContext 函数解析
  37. userInfo, err := utils.GetUserInfoFromContext(storedData)
  38. if err != nil {
  39. t.Errorf("❌ GetUserInfoFromContext 失败: %v", err)
  40. return
  41. }
  42. fmt.Println("\n✅ 测试通过!成功解析用户信息:")
  43. fmt.Printf(" - AccountID: %s\n", userInfo.AccountID)
  44. fmt.Printf(" - ID: %d\n", userInfo.ID)
  45. fmt.Printf(" - Name: %s\n", userInfo.Name)
  46. fmt.Println("=====================================")
  47. }