|
7 | 7 | "fmt" |
8 | 8 | "net/http" |
9 | 9 | "net/http/httptest" |
| 10 | + "sync" |
10 | 11 | "testing" |
11 | 12 |
|
12 | 13 | "github.com/google/uuid" |
@@ -61,3 +62,46 @@ func TestStartTask__ShouldReturnAnErrorIfCreatingTheSameTaskTwice(t *testing.T) |
61 | 62 | assert.Equal(t, 1, len(api.Worker.Tasks), "Tasks map should contain 1 task") |
62 | 63 | assert.NotNil(t, api.Worker.Tasks[testTask.ID], "Persisted task ID should match the one from request") |
63 | 64 | } |
| 65 | + |
| 66 | +func TestStartTask__AllButOneRequestsShouldFailIfCreatingTheSameTaskSimultaneously(t *testing.T) { |
| 67 | + api := &worker.Api{ |
| 68 | + Worker: &worker.Worker{ |
| 69 | + Tasks: make(map[uuid.UUID]*task.Task), |
| 70 | + }, |
| 71 | + } |
| 72 | + testTask := helper.PrintFileTask("print-task", helper.HostsFilePath) |
| 73 | + numOfRequests := 10 |
| 74 | + requests := make([]*http.Request, numOfRequests) |
| 75 | + responseRecorders := make([]*httptest.ResponseRecorder, numOfRequests) |
| 76 | + |
| 77 | + var wg sync.WaitGroup |
| 78 | + for i := range numOfRequests { |
| 79 | + wg.Add(1) |
| 80 | + |
| 81 | + requests[i] = helper.NewTaskPostRequest(testTask) |
| 82 | + responseRecorders[i] = httptest.NewRecorder() |
| 83 | + |
| 84 | + go func() { |
| 85 | + defer wg.Done() |
| 86 | + |
| 87 | + api.HandleCreateTask(responseRecorders[i], requests[i]) |
| 88 | + }() |
| 89 | + } |
| 90 | + |
| 91 | + wg.Wait() |
| 92 | + |
| 93 | + succeededRequests, conflictedRequests := 0, 0 |
| 94 | + for i := range numOfRequests { |
| 95 | + switch responseRecorders[i].Code { |
| 96 | + case http.StatusCreated: |
| 97 | + succeededRequests++ |
| 98 | + case http.StatusConflict: |
| 99 | + conflictedRequests++ |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + assert.Equal(t, 1, succeededRequests, "There should be only 1 succeeded request") |
| 104 | + assert.Equal(t, numOfRequests-1, conflictedRequests, "There should be only N-1 conflicted requests") |
| 105 | + assert.Equal(t, 1, len(api.Worker.Tasks), "Tasks map should contain 1 task") |
| 106 | + assert.NotNil(t, api.Worker.Tasks[testTask.ID], "Persisted task ID should match the one from request") |
| 107 | +} |
0 commit comments