OSDN Git Service

new repo
[bytom/vapor.git] / vendor / github.com / tendermint / tmlibs / autofile / autofile_test.go
1 package autofile
2
3 import (
4         "os"
5         "sync/atomic"
6         "syscall"
7         "testing"
8         "time"
9
10         cmn "github.com/tendermint/tmlibs/common"
11 )
12
13 func TestSIGHUP(t *testing.T) {
14
15         // First, create an AutoFile writing to a tempfile dir
16         file, name := cmn.Tempfile("sighup_test")
17         if err := file.Close(); err != nil {
18                 t.Fatalf("Error creating tempfile: %v", err)
19         }
20         // Here is the actual AutoFile
21         af, err := OpenAutoFile(name)
22         if err != nil {
23                 t.Fatalf("Error creating autofile: %v", err)
24         }
25
26         // Write to the file.
27         _, err = af.Write([]byte("Line 1\n"))
28         if err != nil {
29                 t.Fatalf("Error writing to autofile: %v", err)
30         }
31         _, err = af.Write([]byte("Line 2\n"))
32         if err != nil {
33                 t.Fatalf("Error writing to autofile: %v", err)
34         }
35
36         // Move the file over
37         err = os.Rename(name, name+"_old")
38         if err != nil {
39                 t.Fatalf("Error moving autofile: %v", err)
40         }
41
42         // Send SIGHUP to self.
43         oldSighupCounter := atomic.LoadInt32(&sighupCounter)
44         syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
45
46         // Wait a bit... signals are not handled synchronously.
47         for atomic.LoadInt32(&sighupCounter) == oldSighupCounter {
48                 time.Sleep(time.Millisecond * 10)
49         }
50
51         // Write more to the file.
52         _, err = af.Write([]byte("Line 3\n"))
53         if err != nil {
54                 t.Fatalf("Error writing to autofile: %v", err)
55         }
56         _, err = af.Write([]byte("Line 4\n"))
57         if err != nil {
58                 t.Fatalf("Error writing to autofile: %v", err)
59         }
60         if err := af.Close(); err != nil {
61                 t.Fatalf("Error closing autofile")
62         }
63
64         // Both files should exist
65         if body := cmn.MustReadFile(name + "_old"); string(body) != "Line 1\nLine 2\n" {
66                 t.Errorf("Unexpected body %s", body)
67         }
68         if body := cmn.MustReadFile(name); string(body) != "Line 3\nLine 4\n" {
69                 t.Errorf("Unexpected body %s", body)
70         }
71 }