service_test.go 988 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2015 Daniel Theophanes.
  2. // Use of this source code is governed by a zlib-style
  3. // license that can be found in the LICENSE file.
  4. package service_test
  5. import (
  6. "testing"
  7. "time"
  8. "github.com/kardianos/service"
  9. )
  10. func TestRunInterrupt(t *testing.T) {
  11. p := &program{}
  12. sc := &service.Config{
  13. Name: "go_service_test",
  14. }
  15. s, err := service.New(p, sc)
  16. if err != nil {
  17. t.Fatalf("New err: %s", err)
  18. }
  19. go func() {
  20. <-time.After(1 * time.Second)
  21. interruptProcess(t)
  22. }()
  23. go func() {
  24. for i := 0; i < 25 && p.numStopped == 0; i++ {
  25. <-time.After(200 * time.Millisecond)
  26. }
  27. if p.numStopped == 0 {
  28. t.Fatal("Run() hasn't been stopped")
  29. }
  30. }()
  31. if err = s.Run(); err != nil {
  32. t.Fatalf("Run() err: %s", err)
  33. }
  34. }
  35. type program struct {
  36. numStopped int
  37. }
  38. func (p *program) Start(s service.Service) error {
  39. go p.run()
  40. return nil
  41. }
  42. func (p *program) run() {
  43. // Do work here
  44. }
  45. func (p *program) Stop(s service.Service) error {
  46. p.numStopped++
  47. return nil
  48. }