|
| 1 | +// Licensed to Elasticsearch B.V. under one or more contributor |
| 2 | +// license agreements. See the NOTICE file distributed with |
| 3 | +// this work for additional information regarding copyright |
| 4 | +// ownership. Elasticsearch B.V. licenses this file to you under |
| 5 | +// the Apache License, Version 2.0 (the "License"); you may |
| 6 | +// not use this file except in compliance with the License. |
| 7 | +// You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +package file |
| 19 | + |
| 20 | +import ( |
| 21 | + "os" |
| 22 | + "path/filepath" |
| 23 | + "testing" |
| 24 | + "time" |
| 25 | + |
| 26 | + "github.com/stretchr/testify/require" |
| 27 | +) |
| 28 | + |
| 29 | +// TestSafeFileRotate creates two files, dest and src, and calls |
| 30 | +// SafeFileRotate to replace dest with src. However, before the test |
| 31 | +// makes that call, it deliberately keeps a handle open on dest for |
| 32 | +// a short period of time to ensure that the rotation takes place anyway |
| 33 | +// after the handle has been released. |
| 34 | +func TestSafeFileRotate(t *testing.T) { |
| 35 | + // Create destination file |
| 36 | + tmpDir := t.TempDir() |
| 37 | + dest := filepath.Join(tmpDir, "dest.txt") |
| 38 | + err := os.WriteFile(dest, []byte("existing content"), 0644) |
| 39 | + require.NoError(t, err) |
| 40 | + |
| 41 | + // Create source file |
| 42 | + src := filepath.Join(tmpDir, "src.txt") |
| 43 | + err = os.WriteFile(src, []byte("new content"), 0644) |
| 44 | + require.NoError(t, err) |
| 45 | + |
| 46 | + // Open handle on dest file for 1.5 seconds |
| 47 | + destFile, err := os.Open(dest) |
| 48 | + require.NoError(t, err) |
| 49 | + time.AfterFunc(1500*time.Millisecond, func() { |
| 50 | + destFile.Close() // Close the handle after 1.5 seconds |
| 51 | + }) |
| 52 | + defer destFile.Close() |
| 53 | + |
| 54 | + // Try to replace dest with new |
| 55 | + err = SafeFileRotate(dest, src, WithRenameRetries(2*time.Second, 100*time.Millisecond)) |
| 56 | + require.NoError(t, err) |
| 57 | + |
| 58 | + // Check that dest file has been replaced with new file |
| 59 | + data, err := os.ReadFile(dest) |
| 60 | + require.NoError(t, err) |
| 61 | + require.Equal(t, "new content", string(data)) |
| 62 | +} |
0 commit comments