file_system_task_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. package main
  2. import (
  3. "errors"
  4. "strconv"
  5. "testing"
  6. "time"
  7. "imuslab.com/arozos/mod/filesystem"
  8. )
  9. // newTestFileOperationTask registers a task record for testing and returns it
  10. func newTestFileOperationTask(t *testing.T, id string, sizes []int64) *fileOperationTask {
  11. t.Helper()
  12. subtasks := []*fileOperationSubtask{}
  13. totalSize := int64(0)
  14. for _, size := range sizes {
  15. totalSize += size
  16. subtasks = append(subtasks, &fileOperationSubtask{
  17. Filename: "testfile",
  18. Src: "user:/testfile",
  19. Size: size,
  20. Status: FsTask_Pending,
  21. })
  22. }
  23. thisTask := &fileOperationTask{
  24. ID: id,
  25. Owner: "test_user",
  26. Operation: "copy",
  27. Src: "user:/",
  28. Dest: "user:/Desktop/",
  29. FileOperationSignal: filesystem.FsOpr_Continue,
  30. Files: subtasks,
  31. TotalSize: totalSize,
  32. Status: FsTask_Ongoing,
  33. }
  34. wsConnectionStore.Store(id, thisTask)
  35. t.Cleanup(func() {
  36. wsConnectionStore.Delete(id)
  37. })
  38. return thisTask
  39. }
  40. func TestTaskIsFinished(t *testing.T) {
  41. tests := []struct {
  42. name string
  43. status string
  44. want bool
  45. }{
  46. {"pending task is not finished", FsTask_Pending, false},
  47. {"ongoing task is not finished", FsTask_Ongoing, false},
  48. {"completed task is finished", FsTask_Completed, true},
  49. {"errored task is finished", FsTask_Error, true},
  50. {"cancelled task is finished", FsTask_Cancelled, true},
  51. }
  52. for _, tt := range tests {
  53. t.Run(tt.name, func(t *testing.T) {
  54. got := taskIsFinished(&fileOperationTask{Status: tt.status})
  55. if got != tt.want {
  56. t.Errorf("taskIsFinished(%s) = %v, want %v", tt.status, got, tt.want)
  57. }
  58. })
  59. }
  60. }
  61. func TestSumFileOperationDoneSize(t *testing.T) {
  62. tests := []struct {
  63. name string
  64. done []int64
  65. want int64
  66. }{
  67. {"no file", []int64{}, 0},
  68. {"single file", []int64{1024}, 1024},
  69. {"multiple files", []int64{100, 250, 650}, 1000},
  70. }
  71. for _, tt := range tests {
  72. t.Run(tt.name, func(t *testing.T) {
  73. thisTask := &fileOperationTask{}
  74. for _, done := range tt.done {
  75. thisTask.Files = append(thisTask.Files, &fileOperationSubtask{Done: done})
  76. }
  77. if got := sumFileOperationDoneSize(thisTask); got != tt.want {
  78. t.Errorf("sumFileOperationDoneSize() = %d, want %d", got, tt.want)
  79. }
  80. })
  81. }
  82. }
  83. func TestUpdateOngoingFileOperationSubtask(t *testing.T) {
  84. thisTask := newTestFileOperationTask(t, "test_opr_subtask", []int64{1000, 1000})
  85. sig, progress, err := UpdateOngoingFileOperationSubtask(thisTask.ID, 0, "testfile", 500, 1000)
  86. if err != nil {
  87. t.Fatalf("UpdateOngoingFileOperationSubtask() returned error: %v", err)
  88. }
  89. if sig != filesystem.FsOpr_Continue {
  90. t.Errorf("signal = %d, want %d", sig, filesystem.FsOpr_Continue)
  91. }
  92. if thisTask.Files[0].Done != 500 {
  93. t.Errorf("subtask done size = %d, want 500", thisTask.Files[0].Done)
  94. }
  95. if thisTask.DoneSize != 500 {
  96. t.Errorf("task done size = %d, want 500", thisTask.DoneSize)
  97. }
  98. //500 of the 2000 bytes in this operation are done
  99. if progress != 25 || thisTask.Progress != 25 {
  100. t.Errorf("task progress = %v (returned %v), want 25", thisTask.Progress, progress)
  101. }
  102. //A size the file operation reports overrides the one resolved at task creation
  103. if _, _, err := UpdateOngoingFileOperationSubtask(thisTask.ID, 1, "testfile", 250, 3000); err != nil {
  104. t.Fatalf("UpdateOngoingFileOperationSubtask() returned error: %v", err)
  105. }
  106. if thisTask.Files[1].Size != 3000 {
  107. t.Errorf("subtask size = %d, want 3000", thisTask.Files[1].Size)
  108. }
  109. if thisTask.TotalSize != 4000 {
  110. t.Errorf("task total size = %d, want 4000", thisTask.TotalSize)
  111. }
  112. //Bytes beyond the size of a file are clamped rather than trusted
  113. if _, _, err := UpdateOngoingFileOperationSubtask(thisTask.ID, 0, "testfile", 999999, 0); err != nil {
  114. t.Fatalf("UpdateOngoingFileOperationSubtask() returned error: %v", err)
  115. }
  116. if thisTask.Files[0].Done != 1000 {
  117. t.Errorf("subtask done size = %d, want it clamped to 1000", thisTask.Files[0].Done)
  118. }
  119. //Out of range subtask index should not panic nor change the per file records
  120. if _, _, err := UpdateOngoingFileOperationSubtask(thisTask.ID, 9, "testfile", 100, 100); err != nil {
  121. t.Fatalf("UpdateOngoingFileOperationSubtask() with out of range index returned error: %v", err)
  122. }
  123. //Unknown operation id must return an error
  124. if _, _, err := UpdateOngoingFileOperationSubtask("no_such_opr", 0, "testfile", 10, 10); err == nil {
  125. t.Error("UpdateOngoingFileOperationSubtask() with unknown oprid should return an error")
  126. }
  127. }
  128. // A small file next to a large one must not count for the same share of the bar
  129. func TestRecalculateFileOperationProgressIsSizeWeighted(t *testing.T) {
  130. //One 1 KB file and one 4 GB file
  131. small := int64(1024)
  132. large := int64(4 * 1024 * 1024 * 1024)
  133. thisTask := newTestFileOperationTask(t, "test_opr_weighted", []int64{small, large})
  134. //The small file is done, the large one has not started
  135. MarkFileOperationSubtaskEnded(thisTask.ID, 0, "")
  136. if thisTask.Progress > 1 {
  137. t.Errorf("progress = %v after the small file finished, want it near 0", thisTask.Progress)
  138. }
  139. //Half of the large file is through
  140. if _, _, err := UpdateOngoingFileOperationSubtask(thisTask.ID, 1, "big", large/2, large); err != nil {
  141. t.Fatalf("UpdateOngoingFileOperationSubtask() returned error: %v", err)
  142. }
  143. if thisTask.Progress < 49 || thisTask.Progress > 51 {
  144. t.Errorf("progress = %v with half the large file done, want about 50", thisTask.Progress)
  145. }
  146. }
  147. // Operations whose file sizes could not be resolved still report something sane
  148. func TestRecalculateFileOperationProgressWithoutSizes(t *testing.T) {
  149. thisTask := newTestFileOperationTask(t, "test_opr_nosize", []int64{0, 0})
  150. thisTask.Files[0].Progress = 100
  151. thisTask.Files[1].Progress = 0
  152. recalculateFileOperationProgress(thisTask)
  153. if thisTask.Progress != 50 {
  154. t.Errorf("progress = %v, want 50 when falling back to equal weighting", thisTask.Progress)
  155. }
  156. }
  157. func TestMarkFileOperationSubtaskEnded(t *testing.T) {
  158. thisTask := newTestFileOperationTask(t, "test_opr_subtask_end", []int64{800, 200})
  159. MarkFileOperationSubtaskEnded(thisTask.ID, 0, "")
  160. if thisTask.Files[0].Status != FsTask_Completed {
  161. t.Errorf("subtask status = %s, want %s", thisTask.Files[0].Status, FsTask_Completed)
  162. }
  163. if thisTask.Files[0].Done != 800 || thisTask.DoneSize != 800 {
  164. t.Errorf("done size = %d / %d, want 800 / 800", thisTask.Files[0].Done, thisTask.DoneSize)
  165. }
  166. MarkFileOperationSubtaskEnded(thisTask.ID, 1, "Source file not exists")
  167. if thisTask.Files[1].Status != FsTask_Error {
  168. t.Errorf("subtask status = %s, want %s", thisTask.Files[1].Status, FsTask_Error)
  169. }
  170. if thisTask.Files[1].Error != "Source file not exists" {
  171. t.Errorf("subtask error = %q, want %q", thisTask.Files[1].Error, "Source file not exists")
  172. }
  173. }
  174. func TestSetFileOperationTaskEnded(t *testing.T) {
  175. tests := []struct {
  176. name string
  177. endingSignal int
  178. errmsg string
  179. wantStatus string
  180. }{
  181. {"normal completion", filesystem.FsOpr_Continue, "", FsTask_Completed},
  182. {"cancelled by user", filesystem.FsOpr_Cancel, "", FsTask_Cancelled},
  183. {"ended with error", filesystem.FsOpr_Error, "Access Denied", FsTask_Error},
  184. }
  185. for i, tt := range tests {
  186. t.Run(tt.name, func(t *testing.T) {
  187. thisTask := newTestFileOperationTask(t, "test_opr_end_"+string(rune('a'+i)), []int64{500})
  188. SetFileOperationTaskEnded(thisTask.ID, tt.endingSignal, tt.errmsg)
  189. if thisTask.Status != tt.wantStatus {
  190. t.Errorf("task status = %s, want %s", thisTask.Status, tt.wantStatus)
  191. }
  192. if thisTask.EndTime == 0 {
  193. t.Error("task end time should be set after the task ended")
  194. }
  195. if !taskIsFinished(thisTask) {
  196. t.Error("task should be reported as finished")
  197. }
  198. if thisTask.Files[0].Status == FsTask_Pending {
  199. t.Error("subtask should not be left in pending state after the task ended")
  200. }
  201. })
  202. }
  203. }
  204. func TestFileOperationCancelled(t *testing.T) {
  205. tests := []struct {
  206. name string
  207. signal int
  208. want bool
  209. }{
  210. {"running", filesystem.FsOpr_Continue, false},
  211. {"paused", filesystem.FsOpr_Pause, false},
  212. {"cancelled", filesystem.FsOpr_Cancel, true},
  213. }
  214. for _, tt := range tests {
  215. t.Run(tt.name, func(t *testing.T) {
  216. thisTask := newTestFileOperationTask(t, "test_opr_cancelled_"+tt.name, []int64{100})
  217. thisTask.FileOperationSignal = tt.signal
  218. if got := fileOperationCancelled(thisTask.ID); got != tt.want {
  219. t.Errorf("fileOperationCancelled() = %v, want %v", got, tt.want)
  220. }
  221. })
  222. }
  223. if fileOperationCancelled("test_opr_not_exists") {
  224. t.Error("an unknown operation should not be reported as cancelled")
  225. }
  226. }
  227. // A file operation stopped by the user reports the abort as an error on its way
  228. // out. That must be recorded as a cancellation, not as a failure.
  229. func TestSetFileOperationTaskEndedAfterUserCancel(t *testing.T) {
  230. thisTask := newTestFileOperationTask(t, "test_opr_usercancel", []int64{500})
  231. thisTask.FileOperationSignal = filesystem.FsOpr_Cancel
  232. MarkFileOperationSubtaskEnded(thisTask.ID, 0, "Operation cancelled by user")
  233. SetFileOperationTaskEnded(thisTask.ID, filesystem.FsOpr_Error, "Operation cancelled by user")
  234. if thisTask.Status != FsTask_Cancelled {
  235. t.Errorf("task status = %s, want %s", thisTask.Status, FsTask_Cancelled)
  236. }
  237. if thisTask.Error != "" {
  238. t.Errorf("task error = %q, want it cleared", thisTask.Error)
  239. }
  240. if thisTask.Files[0].Status != FsTask_Cancelled {
  241. t.Errorf("subtask status = %s, want %s", thisTask.Files[0].Status, FsTask_Cancelled)
  242. }
  243. if thisTask.Files[0].Error != "" {
  244. t.Errorf("subtask error = %q, want it cleared", thisTask.Files[0].Error)
  245. }
  246. }
  247. func TestGetAllFileOperationForUser(t *testing.T) {
  248. ongoing := newTestFileOperationTask(t, "test_opr_list_1", []int64{100})
  249. finished := newTestFileOperationTask(t, "test_opr_list_2", []int64{100})
  250. SetFileOperationTaskEnded(finished.ID, filesystem.FsOpr_Continue, "")
  251. onlyOngoing := GetAllFileOperationForUser("test_user", false)
  252. if len(onlyOngoing) != 1 || onlyOngoing[0].ID != ongoing.ID {
  253. t.Errorf("expecting only the ongoing task to be listed, got %d task(s)", len(onlyOngoing))
  254. }
  255. all := GetAllFileOperationForUser("test_user", true)
  256. if len(all) != 2 {
  257. t.Errorf("expecting 2 tasks to be listed, got %d", len(all))
  258. }
  259. if len(all) == 2 && all[0].ID > all[1].ID {
  260. t.Error("task listing should be sorted by operation id")
  261. }
  262. if len(GetAllFileOperationForUser("another_user", true)) != 0 {
  263. t.Error("tasks of a user should not be visible to another user")
  264. }
  265. }
  266. func TestApplyFileOperationControl(t *testing.T) {
  267. thisTask := newTestFileOperationTask(t, "test_opr_control", []int64{100})
  268. if err := ApplyFileOperationControl("test_user", "pause", thisTask.ID); err != nil {
  269. t.Fatalf("pause returned error: %v", err)
  270. }
  271. if thisTask.FileOperationSignal != filesystem.FsOpr_Pause {
  272. t.Errorf("signal = %d, want %d", thisTask.FileOperationSignal, filesystem.FsOpr_Pause)
  273. }
  274. if err := ApplyFileOperationControl("test_user", "continue", thisTask.ID); err != nil {
  275. t.Fatalf("continue returned error: %v", err)
  276. }
  277. if thisTask.FileOperationSignal != filesystem.FsOpr_Continue {
  278. t.Errorf("signal = %d, want %d", thisTask.FileOperationSignal, filesystem.FsOpr_Continue)
  279. }
  280. //A running task cannot be removed from the listing
  281. if err := ApplyFileOperationControl("test_user", "remove", thisTask.ID); err == nil {
  282. t.Error("removing a running task should return an error")
  283. }
  284. //Another user must not be able to control this task
  285. if err := ApplyFileOperationControl("another_user", "cancel", thisTask.ID); err == nil {
  286. t.Error("controlling a task of another user should return an error")
  287. }
  288. //Unsupported commands are rejected
  289. if err := ApplyFileOperationControl("test_user", "explode", thisTask.ID); err == nil {
  290. t.Error("unsupported command should return an error")
  291. }
  292. //A finished task can be removed
  293. SetFileOperationTaskEnded(thisTask.ID, filesystem.FsOpr_Continue, "")
  294. if err := ApplyFileOperationControl("test_user", "remove", thisTask.ID); err != nil {
  295. t.Fatalf("removing a finished task returned error: %v", err)
  296. }
  297. if _, err := GetOngoingFileOperationByOprID(thisTask.ID); err == nil {
  298. t.Error("the removed task should no longer exist in the store")
  299. }
  300. }
  301. // Only a move can be handed to the storage as a rename. The paths of a move are
  302. // resolved against the running storage pools, which a unit test has none of, so
  303. // only the operation types are covered here.
  304. func TestFileOperationCanBeRenamed(t *testing.T) {
  305. tests := []string{"copy", "zip", "unzip", ""}
  306. for _, operation := range tests {
  307. t.Run("operation "+operation, func(t *testing.T) {
  308. if fileOperationCanBeRenamed(operation, []string{"user:/a.txt"}, "user:/Desktop/") {
  309. t.Errorf("a %q operation should never be treated as a rename", operation)
  310. }
  311. })
  312. }
  313. }
  314. func TestClearExpiredFileOperationRecords(t *testing.T) {
  315. //An operation that is still running is never touched
  316. running := newTestFileOperationTask(t, "test_opr_expire_running", []int64{100})
  317. //A freshly finished operation is kept until a connected dialog has seen it
  318. justDone := newTestFileOperationTask(t, "test_opr_expire_fresh", []int64{100})
  319. SetFileOperationTaskEnded(justDone.ID, filesystem.FsOpr_Continue, "")
  320. //An operation that finished a while ago is cleared on its own
  321. oldDone := newTestFileOperationTask(t, "test_opr_expire_done", []int64{100})
  322. SetFileOperationTaskEnded(oldDone.ID, filesystem.FsOpr_Continue, "")
  323. oldDone.EndTime = time.Now().Unix() - fileOprFinishedRecordTTL - 5
  324. //So is one the user cancelled
  325. oldCancelled := newTestFileOperationTask(t, "test_opr_expire_cancelled", []int64{100})
  326. SetFileOperationTaskEnded(oldCancelled.ID, filesystem.FsOpr_Cancel, "")
  327. oldCancelled.EndTime = time.Now().Unix() - fileOprFinishedRecordTTL - 5
  328. //A failure is kept so the user can still look at it later
  329. oldError := newTestFileOperationTask(t, "test_opr_expire_error", []int64{100})
  330. SetFileOperationTaskEnded(oldError.ID, filesystem.FsOpr_Error, "Access Denied")
  331. oldError.EndTime = time.Now().Unix() - fileOprFinishedRecordTTL*100
  332. clearExpiredFileOperationRecords()
  333. kept := []struct {
  334. name string
  335. id string
  336. want bool
  337. }{
  338. {"running operation", running.ID, true},
  339. {"operation that just finished", justDone.ID, true},
  340. {"operation finished long ago", oldDone.ID, false},
  341. {"operation cancelled long ago", oldCancelled.ID, false},
  342. {"failed operation", oldError.ID, true},
  343. }
  344. for _, tt := range kept {
  345. t.Run(tt.name, func(t *testing.T) {
  346. _, err := GetOngoingFileOperationByOprID(tt.id)
  347. if (err == nil) != tt.want {
  348. t.Errorf("record still exists = %v, want %v", err == nil, tt.want)
  349. }
  350. })
  351. }
  352. }
  353. func TestClearExpiredFileOperationRecordsTrimsErrorBacklog(t *testing.T) {
  354. //Failures are kept, but not without a bound
  355. newest := ""
  356. for i := 0; i < fileOprErrorRecordLimit+5; i++ {
  357. thisTask := newTestFileOperationTask(t, "test_opr_backlog_"+strconv.Itoa(i), []int64{100})
  358. SetFileOperationTaskEnded(thisTask.ID, filesystem.FsOpr_Error, "Access Denied")
  359. thisTask.EndTime = time.Now().Unix() - int64(fileOprErrorRecordLimit+5-i)
  360. newest = thisTask.ID
  361. }
  362. clearExpiredFileOperationRecords()
  363. remaining := 0
  364. for _, task := range GetAllFileOperationForUser("test_user", true) {
  365. if task.Status == FsTask_Error {
  366. remaining++
  367. }
  368. }
  369. if remaining != fileOprErrorRecordLimit {
  370. t.Errorf("kept %d failed records, want %d", remaining, fileOprErrorRecordLimit)
  371. }
  372. if _, err := GetOngoingFileOperationByOprID(newest); err != nil {
  373. t.Error("the newest failure should be among the records that are kept")
  374. }
  375. }
  376. func TestClearFinishedFileOperationForUser(t *testing.T) {
  377. ongoing := newTestFileOperationTask(t, "test_opr_clear_1", []int64{100})
  378. finished := newTestFileOperationTask(t, "test_opr_clear_2", []int64{100})
  379. SetFileOperationTaskEnded(finished.ID, filesystem.FsOpr_Continue, "")
  380. ClearFinishedFileOperationForUser("test_user")
  381. if _, err := GetOngoingFileOperationByOprID(finished.ID); err == nil {
  382. t.Error("the finished task should have been cleared")
  383. }
  384. if _, err := GetOngoingFileOperationByOprID(ongoing.ID); err != nil {
  385. t.Error("the ongoing task should not have been cleared")
  386. }
  387. }
  388. func TestFinishTmpZipTask(t *testing.T) {
  389. tests := []struct {
  390. name string
  391. zipErr error
  392. cancelled bool
  393. wantStatus string
  394. wantErrMsg string
  395. }{
  396. {"a completed archive ends as completed", nil, false, FsTask_Completed, ""},
  397. {"a failed archive keeps its error", errors.New("disk full"), false, FsTask_Error, "disk full"},
  398. {"a cancelled archive is not a failure", errors.New("Operation cancelled by user"), true, FsTask_Cancelled, ""},
  399. }
  400. for _, tt := range tests {
  401. t.Run(tt.name, func(t *testing.T) {
  402. task := newTestFileOperationTask(t, "tmpzip_"+strconv.Itoa(int(time.Now().UnixNano())), []int64{100})
  403. task.Operation = "zip"
  404. if tt.cancelled {
  405. task.FileOperationSignal = filesystem.FsOpr_Cancel
  406. }
  407. finishTmpZipTask(task.ID, tt.zipErr)
  408. if task.Status != tt.wantStatus {
  409. t.Errorf("status = %s, want %s", task.Status, tt.wantStatus)
  410. }
  411. if task.Error != tt.wantErrMsg {
  412. t.Errorf("error = %q, want %q", task.Error, tt.wantErrMsg)
  413. }
  414. if task.EndTime == 0 {
  415. t.Errorf("EndTime not set on a finished task")
  416. }
  417. })
  418. }
  419. }