Debian Codegraph @

server/ats/ats_test.go

raw
1 // Copyright 2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package ats
15
16 import (
17 "runtime"
18 "testing"
19 "time"
20 )
21
22 func TestNotRunningValue(t *testing.T) {
23 // Set back to zero in case this test gets run multiple times via --count.
24 utime.Store(0)
25 at := AccessTime()
26 if at == 0 {
27 t.Fatal("Expected non-zero access time")
28 }
29
30 atn := AccessTime()
31 if atn != at {
32 t.Fatal("Did not expect updates to access time")
33 }
34 }
35
36 func TestRegisterAndUnregister(t *testing.T) {
37 ngrp := runtime.NumGoroutine()
38
39 Register()
40 if r := refs.Load(); r != 1 {
41 t.Fatalf("Expected refs to be 1, got %d", r)
42 }
43 // Make sure we have a non-zero time.
44 at := AccessTime()
45 if at == 0 {
46 t.Fatal("Expected non-zero access time")
47 }
48 // Make sure we are updating access time.
49 time.Sleep(2 * TickInterval)
50 atn := AccessTime()
51 if atn == at {
52 t.Fatal("Expected access time to be updated but it was not")
53 }
54
55 // Now unregister.
56 Unregister()
57 if r := refs.Load(); r != 0 {
58 t.Fatalf("Expected refs to be 0, got %d", r)
59 }
60 time.Sleep(TickInterval)
61
62 at = AccessTime()
63 time.Sleep(2 * TickInterval)
64 atn = AccessTime()
65 if atn != at {
66 t.Fatal("Did not expect updates to access time")
67 }
68
69 // Check that we have no additional go routines running.
70 ngra := runtime.NumGoroutine()
71 if ngra != ngrp {
72 t.Fatalf("Expected same number of go routines after removing all registered: %d vs %d", ngrp, ngra)
73 }
74
75 // Check that we spin back up on going from zero to one registered after spinning down.
76 Register()
77 defer Unregister()
78
79 at = AccessTime()
80 time.Sleep(2 * TickInterval)
81 atn = AccessTime()
82 if atn == at {
83 t.Fatal("Expected access time to be updated but it was not")
84 }
85 ngra = runtime.NumGoroutine()
86 if ngra != ngrp+1 {
87 t.Fatalf("Expected to see additional go routine: %d vs %d", ngrp, ngra)
88 }
89 }
90
91 func TestUnbalancedUnregister(t *testing.T) {
92 defer func() {
93 if r := recover(); r == nil {
94 t.Errorf("Expected function to panic, but it did not")
95 }
96 }()
97 Unregister()
98 }