github.com/wtfutil/wtf@v0.43.0/app/scheduler_test.go (about)

     1  package app
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/olebedev/config"
     8  )
     9  
    10  const (
    11  	configExample = `
    12    wtf:
    13      mods:
    14        clocks:
    15          enabled: true
    16          position:
    17            top: 0
    18            left: 0
    19            height: 1
    20            width: 1
    21          refreshInterval: 2`
    22  
    23  	new = `
    24    wtf:
    25      mods:
    26        clocks:
    27          enabled: true
    28          position:
    29            top: 0
    30            left: 0
    31            height: 1
    32            width: 1
    33          refreshInterval: 100ms`
    34  )
    35  
    36  func Test_RefreshInterval(t *testing.T) {
    37  	t.Skip() // slow running test because a ticker is tested
    38  	tests := []struct {
    39  		name         string
    40  		moduleName   string
    41  		config       *config.Config
    42  		testAttempts int
    43  		expected     time.Duration
    44  	}{
    45  		{
    46  			name:       "slow ticking module",
    47  			moduleName: "clocks",
    48  			config: func() *config.Config {
    49  				cfg, _ := config.ParseYaml(configExample)
    50  				return cfg
    51  			}(),
    52  			testAttempts: 10,
    53  			expected:     2 * time.Second,
    54  		},
    55  		{
    56  			name:       "fast ticking module",
    57  			moduleName: "clocks",
    58  			config: func() *config.Config {
    59  				cfg, _ := config.ParseYaml(new)
    60  				return cfg
    61  			}(),
    62  			testAttempts: 10,
    63  			expected:     100 * time.Millisecond,
    64  		},
    65  	}
    66  
    67  	for _, tt := range tests {
    68  		t.Run(tt.name, func(t *testing.T) {
    69  			widget := MakeWidget(nil, nil, tt.moduleName, tt.config, make(chan bool))
    70  
    71  			interval := widget.CommonSettings().RefreshInterval // same declaration as in scheduler.go#Schedule
    72  			timer := time.NewTicker(interval)
    73  
    74  			attempts := 0
    75  			for {
    76  				select {
    77  				case <-timer.C:
    78  					attempts++
    79  					if attempts == tt.testAttempts {
    80  						return
    81  					}
    82  				// allow for small window (50ms) where a timeout is not triggered
    83  				case <-time.After(tt.expected + 50*time.Millisecond):
    84  					t.Error("Timeout")
    85  				}
    86  			}
    87  
    88  		})
    89  	}
    90  }