aboutsummaryrefslogtreecommitdiff
path: root/internal/webui/root_test.go
blob: cd2da0f970b7242494ff0319e30eb7f39674f9e7 (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
package webui

import (
	"net/http"
	"testing"

	"git.adyxax.org/adyxax/trains/pkg/config"
	"git.adyxax.org/adyxax/trains/pkg/database"
	"git.adyxax.org/adyxax/trains/pkg/model"
	"github.com/stretchr/testify/require"
)

type NavitiaMockClient struct {
	departures []model.Departure
	err        error
}

func (c *NavitiaMockClient) GetDepartures(trainStop string) (departures []model.Departure, err error) {
	return c.departures, c.err
}

func TestRootHandler(t *testing.T) {
	// test environment setup
	dbEnv, err := database.InitDB("sqlite3", "file::memory:?_foreign_keys=on")
	require.Nil(t, err)
	err = dbEnv.Migrate()
	require.Nil(t, err)
	user1, err := dbEnv.CreateUser(&model.UserRegistration{Username: "user1", Password: "password1", Email: "julien@adyxax.org"})
	require.Nil(t, err)
	_, err = dbEnv.Login(&model.UserLogin{Username: "user1", Password: "password1"})
	require.Nil(t, err)
	token1, err := dbEnv.CreateSession(user1)
	require.Nil(t, err)
	e := env{
		dbEnv: dbEnv,
		conf:  &config.Config{TrainStop: "test"},
	}
	departures1 := []model.Departure{
		model.Departure{
			Direction: "test direction",
			Arrival:   "20210503T150405",
		},
	}
	e.navitia = &NavitiaMockClient{departures: departures1, err: nil}
	// test GET requests
	runHttpTest(t, &e, rootHandler, &httpTestCase{
		name: "a simple get when not logged in should redirect to the login page",
		input: httpTestInput{
			method: http.MethodGet,
			path:   "/",
		},
		expect: httpTestExpect{
			code:     http.StatusFound,
			location: "/login",
		},
	})
	runHttpTest(t, &e, rootHandler, &httpTestCase{
		name: "a simple get when logged in should display the departure times",
		input: httpTestInput{
			method: http.MethodGet,
			path:   "/",
			cookie: &http.Cookie{Name: sessionCookieName, Value: *token1},
		},
		expect: httpTestExpect{
			code:       http.StatusOK,
			bodyString: "Horaires des prochains trains",
		},
	})
}