Documentation
¶
Overview ¶
Package verify checks the requests a mock server served, of any protocol, from its journal: which came, how many, by when, and in what order. The servers of github.com/caffeine-projects/vlatte/mockhttp and github.com/caffeine-projects/vlatte/mockgrpc embed a Verifier when their setup keeps a journal, so a test calls its methods on the server:
m := mockhttp.MustNew(mockhttp.Setup().Journal("")) // "" keeps the journal in a temporary directory
// ... the code under test sends its requests to m ...
m.VerifyRequests().Method("POST").Path(match.Equal("/orders")).Times(t, 1)
Selecting ¶
Verifier.VerifyRequests selects every request the journal holds, whatever its outcome. Criteria narrow the selection by the fields every protocol has: Requests.Method, Requests.Path, Requests.Target, Requests.Header, Requests.Body, Requests.Status, Requests.Outcome and Requests.MockID. They are the keys of the admin API's queries too. Requests.Matching selects by the request part of the server's own mocks, for what no criterion says, such as an HTTP query parameter or form field.
A check counts from the start of the journal, or from a mark Verifier.JournalMark took, which Requests.Since names: a test that shares a server with others before it counts its own requests only. A journal kept in a directory holds the requests of the server's earlier runs too, which a check without a mark counts.
Checking ¶
Requests.Times, Requests.AtLeast, Requests.AtMost, Requests.Never and Requests.CountIs assert the number of requests a selection holds, and InOrder the order of the requests of several. A check runs now, or waits: Requests.Within until it passes, for a request the code under test sends in the background, and Requests.During as long as it holds. A wait wakes as each request comes, rather than poll.
A failure lists the requests the selection holds and, when it wanted more, those that came closest, with the parts they missed: one line each, without their headers or body, which may hold secrets.
A check never passes on part of the requests it would count. One whose window holds requests the journal dropped to keep its MaxEntries fails with ErrDropped; one of a journal cleared after its mark or as it reads, or from a mark past the journal's newest request, as of a journal that started over, with ErrCleared. A check of a body the journal cut, once the rest of it matches, fails with github.com/caffeine-projects/vlatte/journal.ErrBodyCut.
Check and CheckOrder run checks Spec values describe, for those that verify other than in a test, such as the admin API's QUERY /requests/verify.
Example ¶
package main
import (
"fmt"
"net/http"
"strings"
"github.com/caffeine-projects/vlatte/match"
"github.com/caffeine-projects/vlatte/mockhttp"
)
// exampleT reports what fails on the standard output, as a test's *testing.T reports it in the test's log.
type exampleT struct{}
func (exampleT) Helper() {}
func (exampleT) Logf(format string, a ...any) { fmt.Printf(format+"\n", a...) }
func (exampleT) Error(a ...any) { fmt.Println(a...) }
func (exampleT) Errorf(format string, a ...any) { fmt.Printf(format+"\n", a...) }
// post sends a POST of path to m, as the code under test does.
func post(m *mockhttp.Server, path, body string) {
res, err := http.Post(m.URL(path), "application/json", strings.NewReader(body))
if err != nil {
panic(err)
}
res.Body.Close()
}
func main() {
t := exampleT{} // a test's *testing.T
m := mockhttp.MustNew(mockhttp.Setup().Silent().Journal(""))
m.MustStart()
defer m.Close()
m.MustMock(mockhttp.Postf("/orders").Reply(mockhttp.Created()))
post(m, "/orders", `{"item": "tea"}`)
post(m, "/orders", `{"item": "coffee"}`)
orders := m.VerifyRequests().Method("POST").Path(match.Equal("/orders"))
fmt.Println(orders.Times(t, 2))
fmt.Println(orders.Body(match.JSONPath("$.item", match.Equal("tea"))).Times(t, 1))
fmt.Println(m.VerifyRequests().Status(match.Equal(http.StatusNotFound)).Never(t))
}
Output: true true true
Index ¶
- Variables
- func InOrder[TM vlatte.Mock, A any](t vlatte.TestingT, steps ...Requests[TM, A]) bool
- type Journal
- type Listed
- type Mark
- type Miss
- type Pattern
- type Patterns
- type Protocol
- type Requests
- func (r Requests[TM, A]) AtLeast(t vlatte.TestingT, n int) bool
- func (r Requests[TM, A]) AtMost(t vlatte.TestingT, n int) bool
- func (r Requests[TM, A]) Body(m vlatte.Matcher) Requests[TM, A]
- func (r Requests[TM, A]) Count(ctx context.Context) (int, error)
- func (r Requests[TM, A]) CountIs(t vlatte.TestingT, count vlatte.Matcher) bool
- func (r Requests[TM, A]) During(d time.Duration) Requests[TM, A]
- func (r Requests[TM, A]) Find(ctx context.Context) ([]*journal.Entry, error)
- func (r Requests[TM, A]) Header(name string, m vlatte.Matcher) Requests[TM, A]
- func (r Requests[TM, A]) Matching(patterns ...vlatte.Builder[TM, A]) Requests[TM, A]
- func (r Requests[TM, A]) Method(methods ...string) Requests[TM, A]
- func (r Requests[TM, A]) MockID(m vlatte.Matcher) Requests[TM, A]
- func (r Requests[TM, A]) Never(t vlatte.TestingT) bool
- func (r Requests[TM, A]) Outcome(outcomes ...journal.Outcome) Requests[TM, A]
- func (r Requests[TM, A]) Path(m vlatte.Matcher) Requests[TM, A]
- func (r Requests[TM, A]) Since(mark Mark) Requests[TM, A]
- func (r Requests[TM, A]) Status(m vlatte.Matcher) Requests[TM, A]
- func (r Requests[TM, A]) Target(m vlatte.Matcher) Requests[TM, A]
- func (r Requests[TM, A]) Times(t vlatte.TestingT, n int) bool
- func (r Requests[TM, A]) Within(d time.Duration) Requests[TM, A]
- type Result
- type Spec
- type Verifier
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNoRequestPatterns is the error of a selection by Matching on a server whose protocol takes no patterns. ErrNoRequestPatterns = errors.New("verify: the server takes no request patterns") // ErrInvalidSpec is the error of a check whose [Spec] can't run, such as one without a count. ErrInvalidSpec = errors.New("verify: invalid check") // ErrNoMethod is the error of a selection by Method on a server whose requests have no method, such as gRPC's. ErrNoMethod = errors.New("verify: the server's requests have no method: select by Path") // ErrOtherJournal is the error of a check from a mark of another server's journal. ErrOtherJournal = errors.New("verify: the mark is of another server's journal") // ErrCleared is the error of a check of a journal cleared after its mark, as it read, or during its wait: the // requests it counts are gone. A mark past the journal's newest request, of a journal that started over, is one. ErrCleared = errors.New("verify: the journal was cleared: the requests the check counts are gone") // ErrDropped is the error of a check whose window holds requests the journal dropped to keep its MaxEntries: a // count of those left could pass when it shouldn't. ErrDropped = errors.New("verify: the journal dropped requests the check counts: raise its MaxEntries") )
Functions ¶
func InOrder ¶
InOrder asserts that the server got a request of each step, each after the request of the step before: login, then an order, then logout. Other requests may come between. It checks now: steps that wait, with Within or During, fail it, so wait for the last step with its own check first. Steps of different servers fail it too, as their journals don't share an order. On a failure, it reports with t.Errorf the step that had no request after the one before, and returns false.
Example ¶
package main
import (
"fmt"
"net/http"
"strings"
"github.com/caffeine-projects/vlatte/match"
"github.com/caffeine-projects/vlatte/mockhttp"
"github.com/caffeine-projects/vlatte/verify"
)
// exampleT reports what fails on the standard output, as a test's *testing.T reports it in the test's log.
type exampleT struct{}
func (exampleT) Helper() {}
func (exampleT) Logf(format string, a ...any) { fmt.Printf(format+"\n", a...) }
func (exampleT) Error(a ...any) { fmt.Println(a...) }
func (exampleT) Errorf(format string, a ...any) { fmt.Printf(format+"\n", a...) }
// post sends a POST of path to m, as the code under test does.
func post(m *mockhttp.Server, path, body string) {
res, err := http.Post(m.URL(path), "application/json", strings.NewReader(body))
if err != nil {
panic(err)
}
res.Body.Close()
}
func main() {
t := exampleT{} // a test's *testing.T
m := mockhttp.MustNew(mockhttp.Setup().Silent().Journal(""))
m.MustStart()
defer m.Close()
post(m, "/login", "")
post(m, "/orders", "")
post(m, "/logout", "")
login := m.VerifyRequests().Path(match.Equal("/login"))
logout := m.VerifyRequests().Path(match.Equal("/logout"))
fmt.Println(verify.InOrder(t, login, logout))
}
Output: true
Types ¶
type Journal ¶
type Journal interface {
Find(ctx context.Context, q journal.Query, filters ...journal.Filter) (journal.Page, error)
Count(ctx context.Context, q journal.Query, filters ...journal.Filter) (int, error)
Last() uint64
Cleared() uint64
Trimmed() uint64
Changed() <-chan struct{}
}
Journal is the journal of requests a check reads, such as a *journal.Journal.
type Listed ¶
type Listed struct {
Seq uint64 `json:"seq"`
ID string `json:"id"`
Line string `json:"line"`
Passed int `json:"passed,omitzero"`
Total int `json:"total,omitzero"`
Missed []string `json:"missed,omitempty"`
}
Listed is a request a Result lists: its sequence number, request id and report line, which leaves out its headers and body, and, for one that came close, the parts it passed of those checked and the names of those it missed.
type Mark ¶
type Mark struct {
// contains filtered or unexported fields
}
Mark is a point in a server's journal, which Verifier.JournalMark takes.
type Miss ¶
Miss is how many of the parts a check selects by an entry passed, of how many it was checked by, and the names of those it failed, such as "header Authorization" or "body".
type Pattern ¶
type Pattern interface {
// Match tells whether the pattern matches e. A pattern that reads a part of e the journal cut fails with
// [vlatte.ErrMatching] once the rest of it matches.
Match(ctx context.Context, e *journal.Entry) (bool, error)
// Explain tells which parts of the pattern e passes and which it fails, for a report. A part the journal cut is
// neither.
Explain(ctx context.Context, e *journal.Entry) (Miss, error)
}
Pattern selects the entries of a journal that a protocol's request pattern matches, such as the request part of a mock builder, and names the parts of it an entry fails.
type Patterns ¶
type Patterns[TM vlatte.Mock, A any] interface { RequestPattern(b vlatte.Builder[TM, A]) (Pattern, error) }
Patterns is what the server of a protocol implements to turn b, a builder of its mocks, into a Pattern, for Requests.Matching to select by the request part of its mocks.
type Protocol ¶
type Protocol[TM vlatte.Mock, A any] struct { // Patterns turns builders of the server's mocks into patterns. Nil takes none: [Requests.Matching] fails with // [ErrNoRequestPatterns]. Patterns Patterns[TM, A] // NoMethod tells that the protocol's requests have no method, as gRPC calls: [Requests.Method] fails with // [ErrNoMethod] rather than select none. NoMethod bool }
Protocol tells a Verifier about the requests of a server's protocol.
type Requests ¶
Requests is a selection of the requests of a server's journal, which Verifier.VerifyRequests starts. Its criteria narrow it: all must match. A selection is a value: each method returns a copy, so one is safe to name, reuse and share. A criterion it can't take, or a server with no journal, fails the check, or the read, that ends it.
func (Requests[TM, A]) AtLeast ¶
AtLeast asserts that the selection holds n requests or more. See Times.
func (Requests[TM, A]) AtMost ¶
AtMost asserts that the selection holds n requests or fewer. See Times.
func (Requests[TM, A]) Body ¶
Body selects the requests whose body, as text, m matches, such as with match.JSONPath. A gRPC call's body is its request message as JSON, or the array of a client stream's messages. A check that selects a request whose body the journal cut fails with journal.ErrBodyCut and vlatte.ErrMatching: what was cut may hold what m looks for.
func (Requests[TM, A]) CountIs ¶
CountIs asserts that count, a matcher of an int, matches the number of requests the selection holds, such as match.LTE(3). See Times.
func (Requests[TM, A]) During ¶
During makes the check hold for d: it fails once the count fails, rechecking as each request comes, and passes when d ends, such as for Never to tell that no request came in that time. It ends as Within does on a clear or a close.
func (Requests[TM, A]) Find ¶
Find returns the requests the selection holds, the newest first, with what the journal kept of each: the selection has no limit, so journal.Journal.Find pages them instead. It neither waits nor checks: Within and During count for nothing. It fails, as a check does, rather than return part of the requests: with ErrDropped or ErrCleared.
func (Requests[TM, A]) Header ¶
Header selects the requests whose header named name, in any case, m matches: the matcher gets its first value, or "" for a request without it. gRPC calls have metadata. Each name adds a header to match.
func (Requests[TM, A]) Matching ¶
Matching selects the requests the request part of every pattern matches, as it matches a request: a pattern is a builder of the server's mocks, such as mockhttp.Request().FormField("a", match.Equal("1")), for what no other criterion says, such as an HTTP query parameter, form field or file. Its reply counts for nothing, and one with Times, a scenario, or a part the journal doesn't keep fails the check.
func (Requests[TM, A]) Method ¶
Method selects the requests of any of methods, in any case, such as "POST". gRPC calls have none: Method fails on a gRPC server with ErrNoMethod.
func (Requests[TM, A]) Outcome ¶
Outcome selects the requests of any of outcomes, such as journal.OutcomeUnmatched.
func (Requests[TM, A]) Path ¶
Path selects the requests whose path m matches: the URL's path for HTTP, the full method for gRPC, such as "/helloworld.Greeter/SayHello".
func (Requests[TM, A]) Since ¶
Since selects the requests that came after mark, which Verifier.JournalMark took: none of those before, such as another test's on a server they share. A mark isolates tests that run one after the other: two tests on one server at the same time see each other's requests after their marks. A mark of another server fails the check with ErrOtherJournal, and one the journal was cleared after with ErrCleared.
Example ¶
package main
import (
"fmt"
"net/http"
"strings"
"github.com/caffeine-projects/vlatte/match"
"github.com/caffeine-projects/vlatte/mockhttp"
)
// exampleT reports what fails on the standard output, as a test's *testing.T reports it in the test's log.
type exampleT struct{}
func (exampleT) Helper() {}
func (exampleT) Logf(format string, a ...any) { fmt.Printf(format+"\n", a...) }
func (exampleT) Error(a ...any) { fmt.Println(a...) }
func (exampleT) Errorf(format string, a ...any) { fmt.Printf(format+"\n", a...) }
// post sends a POST of path to m, as the code under test does.
func post(m *mockhttp.Server, path, body string) {
res, err := http.Post(m.URL(path), "application/json", strings.NewReader(body))
if err != nil {
panic(err)
}
res.Body.Close()
}
func main() {
t := exampleT{} // a test's *testing.T
m := mockhttp.MustNew(mockhttp.Setup().Silent().Journal(""))
m.MustStart()
defer m.Close()
post(m, "/orders", "") // another test's request, on the server the tests share
mark := m.JournalMark()
post(m, "/orders", "")
fmt.Println(m.VerifyRequests().Since(mark).Path(match.Equal("/orders")).Times(t, 1))
}
Output: true
func (Requests[TM, A]) Status ¶
Status selects the requests whose answer had a status m matches, an int: an HTTP status, or a gRPC code.
func (Requests[TM, A]) Target ¶
Target selects the requests whose full target m matches, such as the URL with its query string.
func (Requests[TM, A]) Times ¶
Times asserts that the selection holds exactly n requests. On a failure, it reports with t.Errorf the requests it holds and, when it holds fewer, those that came closest, with the parts they missed, and returns false.
func (Requests[TM, A]) Within ¶
Within makes the check wait up to d for its count to pass, such as for a request the code under test sends in the background: it passes once the count does, rechecking as each request comes, and fails when d ends. A count that passes with no request, such as Never's, fails the check: use During. A clear of the journal during the wait fails the check with ErrCleared, and a server that closes with journal.ErrClosed.
Example ¶
package main
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/caffeine-projects/vlatte/match"
"github.com/caffeine-projects/vlatte/mockhttp"
)
// exampleT reports what fails on the standard output, as a test's *testing.T reports it in the test's log.
type exampleT struct{}
func (exampleT) Helper() {}
func (exampleT) Logf(format string, a ...any) { fmt.Printf(format+"\n", a...) }
func (exampleT) Error(a ...any) { fmt.Println(a...) }
func (exampleT) Errorf(format string, a ...any) { fmt.Printf(format+"\n", a...) }
func main() {
t := exampleT{} // a test's *testing.T
m := mockhttp.MustNew(mockhttp.Setup().Silent().Journal(""))
m.MustStart()
defer m.Close()
// The code under test calls the server back in the background, as a webhook does.
go func() {
res, err := http.Post(m.URL("/hooks/paid"), "application/json", strings.NewReader(`{"order": 7}`))
if err == nil {
res.Body.Close()
}
}()
fmt.Println(m.VerifyRequests().Path(match.Equal("/hooks/paid")).Within(5*time.Second).Times(t, 1))
}
Output: true
type Result ¶
type Result struct {
Passed bool `json:"passed"`
Count int `json:"count"`
Waited time.Duration `json:"-"`
Selected []Listed `json:"selected,omitempty"`
Closest []Listed `json:"closest,omitempty"`
// Report says why the check failed, in lines, for a test's failure.
Report string `json:"report,omitempty"`
}
Result is what Check found. Waited is how long a check with a wait waited. Selected and Closest list requests only when the check failed, the newest first: those selected, and, when Count wanted more, those that came closest to being selected.
func Check ¶
Check runs s: it counts the requests s selects and matches Count with the count, now, or on each change of the journal until Within or During ends, without polling. A check that can't count, as when the journal dropped requests it would count, fails with an error rather than pass or fail on part of them: ErrDropped, or ErrCleared for a journal cleared after the mark or during the wait. A journal closed during the wait fails it with journal.ErrClosed.
func CheckOrder ¶
CheckOrder checks that the journal holds a request of each of steps, each after the request of the step before, now: each step's Count, Within and During count for nothing, and steps that wait fail it, as do steps of different journals. Result's Report says, of each step, the request that came after the one before, or that none did. It fails with an error rather than check part of the requests, as Check does.
type Spec ¶
type Spec struct {
Journal Journal
// Query selects by the fields every protocol has. Its After is the mark the check counts from, which Marked says
// is one; its Limit and Before must be 0, as a check counts all it selects.
Query journal.Query
Marked bool
// Outcomes selects the requests of any of them; none selects by Query's Outcome, if any.
Outcomes []journal.Outcome
// Patterns select by the request part of the server's mocks.
Patterns []Pattern
// Count matches the number of requests selected, an int. Expect says it in words for the report, such as
// "exactly 1".
Count vlatte.Matcher
Expect string
// Within waits for Count to pass, up to its length; During waits its length for Count to fail. Neither checks now.
Within time.Duration
During time.Duration
}
Spec is a check of the requests of a journal: those its query, outcomes and patterns select, counted against Count, now or over a wait. Requests fills one for a test; the admin API fills one for a client.
type Verifier ¶
Verifier verifies the requests the journal of a mock server keeps. A server embeds it, next to its vlatte.Base, so its methods are the server's own and every protocol verifies the same way. TM is the server's mock type and A the server, as in vlatte.Base.
func NewVerifier ¶
NewVerifier returns the verifier of the requests j keeps, nil for a server that keeps none, of a server whose protocol p describes.
func (*Verifier[TM, A]) Journal ¶
Journal returns the journal of the requests the server serves, nil when it keeps none.
func (*Verifier[TM, A]) JournalMark ¶
JournalMark returns a mark of the server's journal as it is now, for Requests.Since to select the requests that come after it, and none of those before, such as other tests'.
func (*Verifier[TM, A]) VerifyRequests ¶
VerifyRequests returns the selection of every request the server's journal holds, whatever its outcome, which its methods narrow, then verify or read. A server keeps no journal unless its setup asks for one: every check of one that keeps none fails with journal.ErrNoJournal.
The journal holds the requests the server's mocks get: it doesn't hold those a middleware answers before a mock, such as CORS preflights. A request is in it once the server ends its answer, so a check right after a client gets a small answer finds it; one that a client reads as it comes, such as a stream, or that the code under test sends in the background, needs Requests.Within.