File: service_test.go

package info (click to toggle)
golang-github-kardianos-service 1.2.4-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 324 kB
  • sloc: makefile: 40; sh: 3
file content (86 lines) | stat: -rw-r--r-- 1,629 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2015 Daniel Theophanes.
// Use of this source code is governed by a zlib-style
// license that can be found in the LICENSE file.

package service_test

import (
	"os"
	"testing"
	"time"

	"github.com/kardianos/service"
)

func TestRunInterrupt(t *testing.T) {
	p := &program{}
	sc := &service.Config{
		Name: "go_service_test",
	}
	s, err := service.New(p, sc)
	if err != nil {
		t.Fatalf("New err: %s", err)
	}

	go func() {
		<-time.After(1 * time.Second)
		interruptProcess(t)
	}()

	go func() {
		for i := 0; i < 25 && p.numStopped == 0; i++ {
			<-time.After(200 * time.Millisecond)
		}
		if p.numStopped == 0 {
			t.Fatal("Run() hasn't been stopped")
		}
	}()

	if err = s.Run(); err != nil {
		t.Fatalf("Run() err: %s", err)
	}
}

const testInstallEnv = "TEST_USER_INSTALL"

// Should always run, without asking for any permission
func TestUserRunInterrupt(t *testing.T) {
	if os.Getenv(testInstallEnv) != "1" {
		t.Skipf("env %q is not set to 1", testInstallEnv)
	}
	p := &program{}
	options := make(service.KeyValue)
	options["UserService"] = true
	sc := &service.Config{
		Name:   "go_user_service_test",
		Option: options,
	}
	s, err := service.New(p, sc)
	if err != nil {
		t.Fatalf("New err: %s", err)
	}
	err = s.Install()
	if err != nil {
		t.Errorf("Install err: %s", err)
	}
	err = s.Uninstall()
	if err != nil {
		t.Fatalf("Uninstall err: %s", err)
	}
}

type program struct {
	numStopped int
}

func (p *program) Start(s service.Service) error {
	go p.run()
	return nil
}
func (p *program) run() {
	// Do work here
}
func (p *program) Stop(s service.Service) error {
	p.numStopped++
	return nil
}