1// Copyright 2018 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 collector
15
16import (
17	"context"
18	"testing"
19
20	"github.com/DATA-DOG/go-sqlmock"
21	"github.com/prometheus/client_golang/prometheus"
22	dto "github.com/prometheus/client_model/go"
23	"github.com/smartystreets/goconvey/convey"
24)
25
26func TestScrapeInfoSchemaInnodbTablespaces(t *testing.T) {
27	db, mock, err := sqlmock.New()
28	if err != nil {
29		t.Fatalf("error opening a stub database connection: %s", err)
30	}
31	defer db.Close()
32
33	columns := []string{"SPACE", "NAME", "FILE_FORMAT", "ROW_FORMAT", "SPACE_TYPE", "FILE_SIZE", "ALLOCATED_SIZE"}
34	rows := sqlmock.NewRows(columns).
35		AddRow(1, "sys/sys_config", "Barracuda", "Dynamic", "Single", 100, 100).
36		AddRow(2, "db/compressed", "Barracuda", "Compressed", "Single", 300, 200)
37	mock.ExpectQuery(sanitizeQuery(innodbTablespacesQuery)).WillReturnRows(rows)
38
39	ch := make(chan prometheus.Metric)
40	go func() {
41		if err = (ScrapeInfoSchemaInnodbTablespaces{}).Scrape(context.Background(), db, ch); err != nil {
42			t.Errorf("error calling function on test: %s", err)
43		}
44		close(ch)
45	}()
46
47	expected := []MetricResult{
48		{labels: labelMap{"tablespace_name": "sys/sys_config", "file_format": "Barracuda", "row_format": "Dynamic", "space_type": "Single"}, value: 1, metricType: dto.MetricType_GAUGE},
49		{labels: labelMap{"tablespace_name": "sys/sys_config"}, value: 100, metricType: dto.MetricType_GAUGE},
50		{labels: labelMap{"tablespace_name": "sys/sys_config"}, value: 100, metricType: dto.MetricType_GAUGE},
51		{labels: labelMap{"tablespace_name": "db/compressed", "file_format": "Barracuda", "row_format": "Compressed", "space_type": "Single"}, value: 2, metricType: dto.MetricType_GAUGE},
52		{labels: labelMap{"tablespace_name": "db/compressed"}, value: 300, metricType: dto.MetricType_GAUGE},
53		{labels: labelMap{"tablespace_name": "db/compressed"}, value: 200, metricType: dto.MetricType_GAUGE},
54	}
55	convey.Convey("Metrics comparison", t, func() {
56		for _, expect := range expected {
57			got := readMetric(<-ch)
58			convey.So(expect, convey.ShouldResemble, got)
59		}
60	})
61
62	// Ensure all SQL queries were executed
63	if err := mock.ExpectationsWereMet(); err != nil {
64		t.Errorf("there were unfulfilled exceptions: %s", err)
65	}
66}
67