| 1 |
// Copyright 2018 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 server |
| 15 |
|
| 16 |
import ( |
| 17 |
"fmt" |
| 18 |
"reflect" |
| 19 |
"testing" |
| 20 |
) |
| 21 |
|
| 22 |
func TestRBAppendAndLenAndTotal(t *testing.T) { |
| 23 |
rb := newClosedRingBuffer(10) |
| 24 |
for i := 0; i < 5; i++ { |
| 25 |
rb.append(&closedClient{}) |
| 26 |
} |
| 27 |
if rbl := rb.len(); rbl != 5 { |
| 28 |
t.Fatalf("Expected len of 5, got %d", rbl) |
| 29 |
} |
| 30 |
if rbt := rb.totalConns(); rbt != 5 { |
| 31 |
t.Fatalf("Expected total of 5, got %d", rbt) |
| 32 |
} |
| 33 |
for i := 0; i < 25; i++ { |
| 34 |
rb.append(&closedClient{}) |
| 35 |
} |
| 36 |
if rbl := rb.len(); rbl != 10 { |
| 37 |
t.Fatalf("Expected len of 10, got %d", rbl) |
| 38 |
} |
| 39 |
if rbt := rb.totalConns(); rbt != 30 { |
| 40 |
t.Fatalf("Expected total of 30, got %d", rbt) |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
func (cc *closedClient) String() string { |
| 45 |
return cc.user |
| 46 |
} |
| 47 |
|
| 48 |
func TestRBclosedClients(t *testing.T) { |
| 49 |
rb := newClosedRingBuffer(10) |
| 50 |
|
| 51 |
var ui int |
| 52 |
addConn := func() { |
| 53 |
ui++ |
| 54 |
rb.append(&closedClient{user: fmt.Sprintf("%d", ui)}) |
| 55 |
} |
| 56 |
|
| 57 |
max := 100 |
| 58 |
master := make([]*closedClient, 0, max) |
| 59 |
for i := 1; i <= max; i++ { |
| 60 |
master = append(master, &closedClient{user: fmt.Sprintf("%d", i)}) |
| 61 |
} |
| 62 |
|
| 63 |
testList := func(i int) { |
| 64 |
ccs := rb.closedClients() |
| 65 |
start := int(rb.totalConns()) - len(ccs) |
| 66 |
ms := master[start : start+len(ccs)] |
| 67 |
if !reflect.DeepEqual(ccs, ms) { |
| 68 |
t.Fatalf("test %d: List result did not match master: %+v vs %+v", i, ccs, ms) |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
for i := 0; i < max; i++ { |
| 73 |
addConn() |
| 74 |
testList(i) |
| 75 |
} |
| 76 |
} |