Fix flaky logrotate write test

What does this MR do?

Previously the logrotate TestWriter_Write failed intermittently on Windows machines. In https://gitlab.com/gitlab-org/gitlab-runner/-/jobs/8871462402, we see:

fail 0.02s gitlab.com/gitlab-org/gitlab-runner/helpers/usage_log/logrotate TestWriter_Write
=== RUN   TestWriter_Write
    writer_test.go:47: 
        	Error Trace:	C:/GitLab-Runner/builds/gitlab-org/gitlab-runner/helpers/usage_log/logrotate/writer_test.go:47
        	Error:      	"[{usage-log-2025-01-16-14-33-30.036.json {36000000 63872634810 <nil>}} {usage-log-2025-01-16-14-33-30.025.json {25000000 63872634810 <nil>}} {usage-log-2025-01-16-14-33-30.018.json {18000000 63872634810 <nil>}}]" should have 2 item(s), but has 3
        	Test:       	TestWriter_Write
--- FAIL: TestWriter_Write (0.02s)

The test rotates logs after 5 milliseconds, but when a log is created it may take longer than that to return. Avoid this race condition by not rotating logs right after a file is created.

Why was this MR needed?

Flaky tests are bad!

What's the best way to test this MR?

I couldn't reproduce this on a Windows or Linux machine, but I was able to artificially reproduce the problem by adding a delay:

diff --git a/helpers/usage_log/logrotate/writer.go b/helpers/usage_log/logrotate/writer.go
index b966f059f..5d28ce4a8 100644
--- a/helpers/usage_log/logrotate/writer.go
+++ b/helpers/usage_log/logrotate/writer.go
@@ -58,6 +58,8 @@ func (w *Writer) Write(p []byte) (int, error) {
 		if err != nil {
 			return 0, fmt.Errorf("%w: %v", ErrCreationFailure, err)
 		}
+
+		time.Sleep(100 * time.Millisecond)
 	}
 
 	err := w.rotate()
Edited by Stan Hu

Merge request reports

Loading