-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
96 lines (76 loc) · 2.46 KB
/
context.go
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
85
86
87
88
89
90
91
92
93
94
95
96
package scenario
import (
"bytes"
"context"
"database/sql"
"fmt"
"net/http"
"strings"
"github.com/cucumber/godog"
messages "github.com/cucumber/messages/go/v21"
"github.com/stretchr/testify/require"
"github.com/sergiught/card-games-service/internal/config"
"github.com/sergiught/card-games-service/internal/deck"
)
// DeckContext for the various feature test scenarios.
type DeckContext struct {
config *config.Specification
database *sql.DB
rawResponse *http.Response
response response
errorResponse errorResponse
}
type response struct {
DeckID string `json:"deck_id"`
Shuffled bool `json:"shuffled"`
Remaining int `json:"remaining"`
Cards []deck.FrenchCard `json:"cards"`
}
type errorResponse struct {
Message string `json:"message"`
}
// NewDeckContext returns a new DeckContext.
func NewDeckContext(cfg *config.Specification, db *sql.DB) *DeckContext {
return &DeckContext{
config: cfg,
database: db,
}
}
// ResetContext is triggered after each scenario in order to clean up the data.
func (deckCtx *DeckContext) ResetContext() {
deckCtx.rawResponse = nil
deckCtx.response = response{}
deckCtx.errorResponse = errorResponse{}
}
func (deckCtx *DeckContext) sendRequest(ctx context.Context, method, uri string, body []byte) *http.Response {
request, err := http.NewRequestWithContext(ctx, method, deckCtx.buildURL(uri), bytes.NewBuffer(body))
require.NoError(godog.T(ctx), err)
response, err := http.DefaultClient.Do(request)
require.NoError(godog.T(ctx), err)
return response
}
func (deckCtx *DeckContext) buildURL(uri string) string {
return fmt.Sprintf("http://%s/%s", strings.Trim(deckCtx.config.Server.Address, "/"), strings.Trim(uri, "/"))
}
func (deckCtx *DeckContext) parseCardsTable(ctx context.Context, table *godog.Table) []deck.FrenchCard {
var cards []deck.FrenchCard
headers := table.Rows[0].Cells
for _, row := range table.Rows[1:] {
card := deck.FrenchCard{
Value: row.Cells[getTableColumnIndex(ctx, headers, "value")].Value,
Suit: row.Cells[getTableColumnIndex(ctx, headers, "suit")].Value,
Code: row.Cells[getTableColumnIndex(ctx, headers, "code")].Value,
}
cards = append(cards, card)
}
return cards
}
func getTableColumnIndex(ctx context.Context, cells []*messages.PickleTableCell, header string) int {
for idx, cell := range cells {
if cell.Value == header {
return idx
}
}
godog.T(ctx).Fatalf("header not found in table: %q", header)
return 0
}