aboutsummaryrefslogtreecommitdiff
path: root/userapi/util/phonehomestats_test.go
blob: 6e62210e85b6e856af83e8f8769338d55d311911 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package util

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"golang.org/x/crypto/bcrypt"

	"github.com/matrix-org/dendrite/internal"
	"github.com/matrix-org/dendrite/setup/config"
	"github.com/matrix-org/dendrite/test"
	"github.com/matrix-org/dendrite/test/testrig"
	"github.com/matrix-org/dendrite/userapi/storage"
)

func TestCollect(t *testing.T) {
	test.WithAllDatabases(t, func(t *testing.T, dbType test.DBType) {
		b, _, _ := testrig.Base(nil)
		connStr, closeDB := test.PrepareDBConnectionString(t, dbType)
		defer closeDB()
		db, err := storage.NewUserAPIDatabase(b, &config.DatabaseOptions{
			ConnectionString: config.DataSource(connStr),
		}, "localhost", bcrypt.MinCost, 1000, 1000, "")
		if err != nil {
			t.Error(err)
		}

		receivedRequest := make(chan struct{}, 1)
		// create a test server which responds to our call
		srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			var data map[string]interface{}
			if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
				t.Error(err)
			}
			defer r.Body.Close()
			if _, err := w.Write([]byte("{}")); err != nil {
				t.Error(err)
			}

			// verify the received data matches our expectations
			dbEngine, ok := data["database_engine"]
			if !ok {
				t.Errorf("missing database_engine in JSON request: %+v", data)
			}
			version, ok := data["version"]
			if !ok {
				t.Errorf("missing version in JSON request: %+v", data)
			}
			if version != internal.VersionString() {
				t.Errorf("unexpected version: %q, expected %q", version, internal.VersionString())
			}
			switch {
			case dbType == test.DBTypeSQLite && dbEngine != "SQLite":
				t.Errorf("unexpected database_engine: %s", dbEngine)
			case dbType == test.DBTypePostgres && dbEngine != "Postgres":
				t.Errorf("unexpected database_engine: %s", dbEngine)
			}
			close(receivedRequest)
		}))
		defer srv.Close()

		b.Cfg.Global.ReportStats.Endpoint = srv.URL
		stats := phoneHomeStats{
			prevData:   timestampToRUUsage{},
			serverName: "localhost",
			startTime:  time.Now(),
			cfg:        b.Cfg,
			db:         db,
			isMonolith: false,
			client:     &http.Client{Timeout: time.Second},
		}

		stats.collect()

		select {
		case <-time.After(time.Second * 5):
			t.Error("timed out waiting for response")
		case <-receivedRequest:
		}
	})
}