1// Copyright 2019 The Prometheus 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 14package procfs 15 16import ( 17 "reflect" 18 "testing" 19) 20 21func TestSwaps(t *testing.T) { 22 fs, err := NewFS(procTestFixtures) 23 if err != nil { 24 t.Fatalf("failed to open procfs: %v", err) 25 } 26 27 swaps, err := fs.Swaps() 28 if err != nil { 29 t.Fatalf("failed to get swaps: %v", err) 30 } 31 32 if len(swaps) != 1 { 33 t.Fatalf("expected 1 swap entry, got %d", len(swaps)) 34 } 35 swap := swaps[0] 36 37 if swap.Filename != "/dev/dm-2" { 38 t.Errorf("expected swap.Filename /dev/dm-2, got %s", swap.Filename) 39 } 40 if swap.Type != "partition" { 41 t.Errorf("expected swap.Type partition, got %s", swap.Type) 42 } 43 if swap.Size != 131068 { 44 t.Errorf("expected swap.Size 131068, got %d", swap.Size) 45 } 46 if swap.Used != 176 { 47 t.Errorf("expected swap.Used 176, got %d", swap.Used) 48 } 49 if swap.Priority != -2 { 50 t.Errorf("expected swap.Priority -2, got %d", swap.Priority) 51 } 52} 53 54func TestParseSwapString(t *testing.T) { 55 tests := []struct { 56 name string 57 s string 58 swap *Swap 59 invalid bool 60 }{ 61 { 62 name: "device-mapper volume", 63 s: "/dev/dm-2 partition 131068 1024 -2", 64 invalid: false, 65 swap: &Swap{ 66 Filename: "/dev/dm-2", 67 Type: "partition", 68 Size: 131068, 69 Used: 1024, 70 Priority: -2, 71 }, 72 }, 73 { 74 name: "Swap file", 75 s: "/foo file 1048572 0 -3", 76 invalid: false, 77 swap: &Swap{ 78 Filename: "/foo", 79 Type: "file", 80 Size: 1048572, 81 Used: 0, 82 Priority: -3, 83 }, 84 }, 85 { 86 name: "Invalid number", 87 s: "/dev/sda2 partition hello world -2", 88 invalid: true, 89 }, 90 { 91 name: "Not enough fields", 92 s: "/dev/dm-2 partition 131068 1024", 93 invalid: true, 94 }, 95 } 96 97 for _, tt := range tests { 98 t.Run(tt.name, func(t *testing.T) { 99 swap, err := parseSwapString(tt.s) 100 101 if tt.invalid && err == nil { 102 t.Error("unexpected success") 103 } 104 if !tt.invalid && err != nil { 105 t.Errorf("unexpected error: %w", err) 106 } 107 108 if !reflect.DeepEqual(tt.swap, swap) { 109 t.Errorf("swap:\nwant:\n%+v\nhave:\n%+v", tt.swap, swap) 110 } 111 }) 112 } 113} 114