Debian Codegraph @

xos/pid_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /*
2 * Copyright 2012-2022 Li Kexian
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * A toolkit for Golang development
17 * https://www.likexian.com/
18 */
19
20 package xos
21
22 import (
23 "errors"
24 "os"
25 "testing"
26 "time"
27
28 "github.com/likexian/gokit/assert"
29 "github.com/likexian/gokit/xfile"
30 )
31
32 const (
33 pidFile = "/tmp/testing.pid"
34 )
35
36 func TestValue(t *testing.T) {
37 defer os.Remove(pidFile)
38
39 p := Pid(pidFile)
40 _, err := p.Value()
41 assert.NotNil(t, err)
42
43 err = xfile.WriteText(pidFile, "1")
44 assert.Nil(t, err)
45
46 pid, err := p.Value()
47 assert.Nil(t, err)
48 assert.Equal(t, pid, 1)
49 }
50
51 func TestAlive(t *testing.T) {
52 defer os.Remove(pidFile)
53
54 p := Pid(pidFile)
55 _, err := p.Alive()
56 assert.NotNil(t, err)
57
58 err = xfile.WriteText(pidFile, "88888888")
59 assert.Nil(t, err)
60
61 _, err = p.Alive()
62 assert.NotNil(t, err)
63
64 err = xfile.WriteText(pidFile, "1")
65 assert.Nil(t, err)
66
67 pid, err := p.Alive()
68 assert.Nil(t, err)
69 assert.Equal(t, pid, 1)
70 }
71
72 func TestCreate(t *testing.T) {
73 defer os.Remove(pidFile)
74
75 err := xfile.WriteText(pidFile, "1")
76 assert.Nil(t, err)
77
78 p := Pid(pidFile)
79 pid, err := p.Create()
80 assert.NotNil(t, err)
81 assert.Equal(t, pid, 1)
82
83 err = xfile.WriteText(pidFile, "88888888")
84 assert.Nil(t, err)
85
86 _, err = p.Create()
87 assert.Nil(t, err)
88 }
89
90 func TestConcurrency(t *testing.T) {
91 defer os.Remove(pidFile)
92
93 p := Pid(pidFile)
94 for i := 0; i < 1000; i++ {
95 go func() {
96 _, err := p.Create()
97 if err != nil {
98 if !errors.Is(err, ErrPidLockFailed) && !errors.Is(err, ErrPidExists) {
99 t.Errorf("Unexcepted error: %s", err)
100 }
101 }
102 }()
103 }
104
105 time.Sleep(1 * time.Second)
106 }