1// Copyright 2014 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 prometheus
15
16import (
17	"math"
18	"testing"
19
20	dto "github.com/coreos/etcd/Godeps/_workspace/src/github.com/prometheus/client_model/go"
21)
22
23func TestCounterAdd(t *testing.T) {
24	counter := NewCounter(CounterOpts{
25		Name:        "test",
26		Help:        "test help",
27		ConstLabels: Labels{"a": "1", "b": "2"},
28	}).(*counter)
29	counter.Inc()
30	if expected, got := 1., math.Float64frombits(counter.valBits); expected != got {
31		t.Errorf("Expected %f, got %f.", expected, got)
32	}
33	counter.Add(42)
34	if expected, got := 43., math.Float64frombits(counter.valBits); expected != got {
35		t.Errorf("Expected %f, got %f.", expected, got)
36	}
37
38	if expected, got := "counter cannot decrease in value", decreaseCounter(counter).Error(); expected != got {
39		t.Errorf("Expected error %q, got %q.", expected, got)
40	}
41
42	m := &dto.Metric{}
43	counter.Write(m)
44
45	if expected, got := `label:<name:"a" value:"1" > label:<name:"b" value:"2" > counter:<value:43 > `, m.String(); expected != got {
46		t.Errorf("expected %q, got %q", expected, got)
47	}
48}
49
50func decreaseCounter(c *counter) (err error) {
51	defer func() {
52		if e := recover(); e != nil {
53			err = e.(error)
54		}
55	}()
56	c.Add(-1)
57	return nil
58}
59