jira_client_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package common
  2. import (
  3. "context"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. "time"
  8. )
  9. func TestJiraClient_GetProjectAndIssueInfo(t *testing.T) {
  10. t.Helper()
  11. mux := http.NewServeMux()
  12. mux.HandleFunc("/rest/api/2/project/OPMS", func(w http.ResponseWriter, r *http.Request) {
  13. if r.Method != http.MethodGet {
  14. t.Fatalf("unexpected method for project endpoint: %s", r.Method)
  15. }
  16. w.Header().Set("Content-Type", "application/json")
  17. _, _ = w.Write([]byte(`{"id":"10001","key":"OPMS","name":"OPMS Project"}`))
  18. })
  19. mux.HandleFunc("/rest/api/2/issue/OPMS-123", func(w http.ResponseWriter, r *http.Request) {
  20. if r.Method != http.MethodGet {
  21. t.Fatalf("unexpected method for issue endpoint: %s", r.Method)
  22. }
  23. if got := r.URL.Query().Get("fields"); got != "summary,description" {
  24. t.Fatalf("unexpected fields query, got=%q", got)
  25. }
  26. w.Header().Set("Content-Type", "application/json")
  27. _, _ = w.Write([]byte(`{
  28. "id":"20001",
  29. "key":"OPMS-123",
  30. "fields":{
  31. "summary":"测试任务",
  32. "description":"测试任务描述"
  33. }
  34. }`))
  35. })
  36. server := httptest.NewServer(mux)
  37. defer server.Close()
  38. client, err := NewJiraClient(JiraClientConfig{
  39. BaseURL: server.URL,
  40. AuthType: JiraAuthTypeBasic,
  41. Username: "tester",
  42. Password: "tester_password",
  43. Timeout: 5 * time.Second,
  44. })
  45. if err != nil {
  46. t.Fatalf("NewJiraClient() error = %v", err)
  47. }
  48. ctx := context.Background()
  49. project, _, err := client.RawClient().Project.GetWithContext(ctx, "OPMS")
  50. if err != nil {
  51. t.Fatalf("Project.GetWithContext() error = %v", err)
  52. }
  53. if project == nil {
  54. t.Fatal("project is nil")
  55. }
  56. if project.Key != "OPMS" || project.Name != "OPMS Project" {
  57. t.Fatalf("unexpected project, key=%q name=%q", project.Key, project.Name)
  58. }
  59. issue, err := client.GetIssue(ctx, "OPMS-123", "summary", "description")
  60. if err != nil {
  61. t.Fatalf("GetIssue() error = %v", err)
  62. }
  63. if issue == nil || issue.Fields == nil {
  64. t.Fatal("issue or issue.Fields is nil")
  65. }
  66. if issue.Key != "OPMS-123" {
  67. t.Fatalf("unexpected issue key: %q", issue.Key)
  68. }
  69. if issue.Fields.Summary != "测试任务" || issue.Fields.Description != "测试任务描述" {
  70. t.Fatalf("unexpected issue fields, summary=%q description=%q", issue.Fields.Summary, issue.Fields.Description)
  71. }
  72. }
  73. func TestJiraClient_GetIssue_EmptyIssueKey(t *testing.T) {
  74. client := &JiraClient{}
  75. _, err := client.GetIssue(context.Background(), "")
  76. if err == nil {
  77. t.Fatal("expected error when issueKey is empty, got nil")
  78. }
  79. }