From c0fda06a94410a56f9726404565f0f2abffa88a5 Mon Sep 17 00:00:00 2001 From: CHIKAMATSU Naohiro Date: Thu, 5 Oct 2023 14:47:19 +0900 Subject: [PATCH 1/2] Fix staticcheck --- .octocov.yml | 11 +- README.md | 78 ++++---- assert.go | 2 +- assert_test.go | 2 +- cookies_test.go | 8 +- diagram_test.go | 2 +- difflib/difflib.go | 60 +++--- difflib/difflib_test.go | 8 +- examples/echo/api_test.go | 13 +- examples/fiber/api_test.go | 12 +- examples/gin/api_test.go | 13 +- examples/ginkgo/server_test.go | 12 +- examples/gorilla/api_test.go | 13 +- examples/graphql/api_test.go | 8 +- examples/httprouter/api_test.go | 12 +- examples/iris/api_test.go | 13 +- examples/mocks/api_test.go | 10 +- .../Makefile | 6 +- .../api_test.go | 24 +-- .../Makefile | 6 +- .../api_test.go | 20 +- .../test/test_support.go | 8 +- .../api_test.go | 24 +-- examples/sequence-diagrams/api_test.go | 14 +- mocks.go | 4 +- mocks/verifier.go | 41 ++-- mocks_test.go | 12 +- spectest.code-workspace | 75 ++++++++ spectest.go | 24 +-- spectest_test.go | 176 +++++++++--------- x/db/db.go | 98 ++++------ 31 files changed, 427 insertions(+), 382 deletions(-) create mode 100644 spectest.code-workspace diff --git a/.octocov.yml b/.octocov.yml index 1e17b9f..37421fa 100644 --- a/.octocov.yml +++ b/.octocov.yml @@ -2,10 +2,13 @@ coverage: if: true acceptable: 80% + badge: + path: docs/coverage.svg testExecutionTime: if: true acceptable: 1:1.1 - acceptable: current <= 1min && diff <= 2sec + badge: + path: docs/time.svg diff: datastores: - artifact://${GITHUB_REPOSITORY} @@ -17,12 +20,6 @@ report: if: is_default_branch datastores: - artifact://${GITHUB_REPOSITORY} -coverage: - badge: - path: docs/coverage.svg codeToTestRatio: badge: path: docs/ratio.svg -testExecutionTime: - badge: - path: docs/time.svg \ No newline at end of file diff --git a/README.md b/README.md index 3dc8f17..bae23f1 100644 --- a/README.md +++ b/README.md @@ -32,16 +32,16 @@ go get -u github.com/go-spectest/spectest | Example | Comment | | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| [gin](https://github.com/go-spectest/apitest/tree/master/examples/gin) | popular martini-like web framework | -| [graphql](https://github.com/go-spectest/apitest/tree/master/examples/graphql) | using gqlgen.com to generate a graphql server | -| [gorilla](https://github.com/go-spectest/apitest/tree/master/examples/gorilla) | the gorilla web toolkit | -| [iris](https://github.com/go-spectest/apitest/tree/master/examples/iris) | iris web framework | -| [echo](https://github.com/go-spectest/apitest/tree/master/examples/echo) | High performance, extensible, minimalist Go web framework | -| [fiber](https://github.com/go-spectest/go-spectest/tree/master/examples/fiber) | Express inspired web framework written in Go | -| [httprouter](https://github.com/go-spectest/apitest/tree/master/examples/httprouter) | High performance HTTP request router that scales well | -| [mocks](https://github.com/go-spectest/apitest/tree/master/examples/mocks) | example mocking out external http calls | -| [sequence diagrams](https://github.com/go-spectest/apitest/tree/master/examples/sequence-diagrams) | generate sequence diagrams from tests | -| [Ginkgo](https://github.com/go-spectest/apitest/tree/master/examples/ginkgo) | Ginkgo BDD test framework| +| [gin](https://github.com/go-spectest/spectest/tree/master/examples/gin) | popular martini-like web framework | +| [graphql](https://github.com/go-spectest/spectest/tree/master/examples/graphql) | using gqlgen.com to generate a graphql server | +| [gorilla](https://github.com/go-spectest/spectest/tree/master/examples/gorilla) | the gorilla web toolkit | +| [iris](https://github.com/go-spectest/spectest/tree/master/examples/iris) | iris web framework | +| [echo](https://github.com/go-spectest/spectest/tree/master/examples/echo) | High performance, extensible, minimalist Go web framework | +| [fiber](https://github.com/go-spectest/spectest/tree/master/examples/fiber) | Express inspired web framework written in Go | +| [httprouter](https://github.com/go-spectest/spectest/tree/master/examples/httprouter) | High performance HTTP request router that scales well | +| [mocks](https://github.com/go-spectest/spectest/tree/master/examples/mocks) | example mocking out external http calls | +| [sequence diagrams](https://github.com/go-spectest/spectest/tree/master/examples/sequence-diagrams) | generate sequence diagrams from tests | +| [Ginkgo](https://github.com/go-spectest/spectest/tree/master/examples/ginkgo) | Ginkgo BDD test framework| ### Companion libraries @@ -67,7 +67,7 @@ This library was influenced by the following software packages: ```go func TestApi(t *testing.T) { - apitest.New(). + spectest.New(). Handler(handler). Get("/user/1234"). Expect(t). @@ -85,7 +85,7 @@ Given the response is `{"a": 12345, "b": [{"key": "c", "value": "result"}]}` ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Get("/hello"). Expect(t). Assert(jsonpath.Contains(`$.b[? @.key=="c"].value`, "result")). @@ -97,7 +97,7 @@ and `jsonpath.Equals` checks for value equality ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Get("/hello"). Expect(t). Assert(jsonpath.Equal(`$.a`, float64(12345))). @@ -109,7 +109,7 @@ func TestApi(t *testing.T) { ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Get("/hello"). Expect(t). Assert(func(res *http.Response, req *http.Request) error { @@ -124,16 +124,16 @@ func TestApi(t *testing.T) { ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Patch("/hello"). Expect(t). Status(http.StatusOK). - Cookies(apitest.Cookie("ABC").Value("12345")). + Cookies(spectest.Cookie("ABC").Value("12345")). CookiePresent("Session-Token"). CookieNotPresent("XXX"). Cookies( - apitest.Cookie("ABC").Value("12345"), - apitest.Cookie("DEF").Value("67890"), + spectest.Cookie("ABC").Value("12345"), + spectest.Cookie("DEF").Value("67890"), ). End() } @@ -143,7 +143,7 @@ func TestApi(t *testing.T) { ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Get("/hello"). Expect(t). Status(http.StatusOK). @@ -155,14 +155,14 @@ func TestApi(t *testing.T) { #### Mocking external http calls ```go -var getUser = apitest.NewMock(). +var getUser = spectest.NewMock(). Get("/user/12345"). RespondWith(). Body(`{"name": "jon", "id": "1234"}`). Status(http.StatusOK). End() -var getPreferences = apitest.NewMock(). +var getPreferences = spectest.NewMock(). Get("/preferences/12345"). RespondWith(). Body(`{"is_contactable": true}`). @@ -170,7 +170,7 @@ var getPreferences = apitest.NewMock(). End() func TestApi(t *testing.T) { - apitest.New(). + spectest.New(). Mocks(getUser, getPreferences). Handler(handler). Get("/hello"). @@ -186,8 +186,8 @@ func TestApi(t *testing.T) { ```go func TestApi(t *testing.T) { - apitest.New(). - Report(apitest.SequenceDiagram()). + spectest.New(). + Report(spectest.SequenceDiagram()). Mocks(getUser, getPreferences). Handler(handler). Get("/hello"). @@ -198,14 +198,14 @@ func TestApi(t *testing.T) { } ``` -It is possible to override the default storage location by passing the formatter instance `Report(apitest.NewSequenceDiagramFormatter(".sequence-diagrams"))`. -You can bring your own formatter too if you want to produce custom output. By default a sequence diagram is rendered on a html page. See the [demo](http://demo-html.apitest.dev.s3-website-eu-west-1.amazonaws.com/) +It is possible to override the default storage location by passing the formatter instance `Report(spectest.NewSequenceDiagramFormatter(".sequence-diagrams"))`. +You can bring your own formatter too if you want to produce custom output. By default a sequence diagram is rendered on a html page. #### Debugging http requests and responses generated by api test and any mocks ```go func TestApi(t *testing.T) { - apitest.New(). + spectest.New(). Debug(). Handler(handler). Get("/hello"). @@ -219,7 +219,7 @@ func TestApi(t *testing.T) { ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Get("/hello"). BasicAuth("username", "password"). Expect(t). @@ -232,7 +232,7 @@ func TestApi(t *testing.T) { ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Get("/hello"). WithContext(context.TODO()). Expect(t). @@ -245,9 +245,9 @@ func TestApi(t *testing.T) { ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Get("/hello"). - Cookies(apitest.Cookie("ABC").Value("12345")). + Cookies(spectest.Cookie("ABC").Value("12345")). Expect(t). Status(http.StatusOK). End() @@ -258,7 +258,7 @@ func TestApi(t *testing.T) { ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Delete("/hello"). Headers(map[string]string{"My-Header": "12345"}). Expect(t). @@ -273,7 +273,7 @@ func TestApi(t *testing.T) { ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Get("/hello"). QueryParams(map[string]string{"a": "1", "b": "2"}). Query("c", "d"). @@ -288,7 +288,7 @@ Providing `{"a": {"b", "c", "d"}` results in parameters encoded as `a=b&a=c&a=d` ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Get("/hello"). QueryCollection(map[string][]string{"a": {"b", "c", "d"}}). Expect(t). @@ -301,7 +301,7 @@ func TestApi(t *testing.T) { ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Post("/hello"). FormData("a", "1"). FormData("b", "2"). @@ -317,7 +317,7 @@ func TestApi(t *testing.T) { ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Post("/hello"). MultipartFormData("a", "1", "2"). MultipartFile("file", "path/to/some.file1", "path/to/some.file2"). @@ -331,8 +331,8 @@ func TestApi(t *testing.T) { ```go func TestApi(t *testing.T) { - apitest.New(). - Observe(func(res *http.Response, req *http.Request, apiTest *apitest.APITest) { + spectest.New(). + Observe(func(res *http.Response, req *http.Request, apiTest *spectest.APITest) { // do something with res and req }). Handler(handler). @@ -349,7 +349,7 @@ This is useful for mutating the request before it is sent to the system under te ```go func TestApi(t *testing.T) { - apitest.Handler(handler). + spectest.Handler(handler). Intercept(func(req *http.Request) { req.URL.RawQuery = "a[]=xxx&a[]=yyy" }). diff --git a/assert.go b/assert.go index b3088ac..2957d92 100644 --- a/assert.go +++ b/assert.go @@ -30,7 +30,7 @@ type failureMessageArgs struct { } // Verifier is the assertion interface allowing consumers to inject a custom assertion implementation. -// It also allows failure scenarios to be tested within apitest +// It also allows failure scenarios to be tested within spectest type Verifier interface { Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool True(t TestingT, value bool, msgAndArgs ...interface{}) bool diff --git a/assert_test.go b/assert_test.go index 42c3820..f628f02 100644 --- a/assert_test.go +++ b/assert_test.go @@ -23,7 +23,7 @@ func TestApiTestAssertStatusCodes(t *testing.T) { response := &http.Response{StatusCode: status} err := test.assertFunc(response, nil) if test.isSuccess && err != nil { - t.Fatalf("Expecteted nil but received %s", err) + t.Fatalf("Expected nil but received %s", err) } else if !test.isSuccess && err == nil { t.Fatalf("Expected error but didn't receive one") } diff --git a/cookies_test.go b/cookies_test.go index d1057cd..0af7668 100644 --- a/cookies_test.go +++ b/cookies_test.go @@ -19,8 +19,8 @@ func TestApiTestCookiesExpectedCookie(t *testing.T) { HTTPOnly(false) ten := 10 - boolt := true - boolf := false + boolTrue := true + boolFalse := false assert.Equal(t, Cookie{ name: toString("Tom"), @@ -29,8 +29,8 @@ func TestApiTestCookiesExpectedCookie(t *testing.T) { domain: toString("in.london"), expires: &expiry, maxAge: &ten, - secure: &boolt, - httpOnly: &boolf, + secure: &boolTrue, + httpOnly: &boolFalse, }, *cookie) } diff --git a/diagram_test.go b/diagram_test.go index 5c2e73e..9e37e92 100644 --- a/diagram_test.go +++ b/diagram_test.go @@ -204,7 +204,7 @@ type FS struct { func (m *FS) create(name string) (*os.File, error) { m.CapturedCreateName = name - file, err := os.CreateTemp("/tmp", "apitest") + file, err := os.CreateTemp("/tmp", "spectest") if err != nil { panic(err) } diff --git a/difflib/difflib.go b/difflib/difflib.go index 1f6632f..766b754 100644 --- a/difflib/difflib.go +++ b/difflib/difflib.go @@ -50,12 +50,14 @@ func calculateRatio(matches, length int) float64 { return 1.0 } +// Match object type Match struct { A int B int Size int } +// OpCode object type OpCode struct { Tag byte I1 int @@ -103,27 +105,28 @@ type SequenceMatcher struct { opCodes []OpCode } +// NewMatcher return new SequenceMatcher func NewMatcher(a, b []string) *SequenceMatcher { m := SequenceMatcher{autoJunk: true} m.SetSeqs(a, b) return &m } -func NewMatcherWithJunk(a, b []string, autoJunk bool, - isJunk func(string) bool) *SequenceMatcher { +// NewMatcherWithJunk return new SequenceMatcher with junk detection. +func NewMatcherWithJunk(a, b []string, autoJunk bool, isJunk func(string) bool) *SequenceMatcher { m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk} m.SetSeqs(a, b) return &m } -// Set two sequences to be compared. +// SetSeqs set two sequences to be compared. func (m *SequenceMatcher) SetSeqs(a, b []string) { m.SetSeq1(a) m.SetSeq2(b) } -// Set the first sequence to be compared. The second sequence to be compared is +// SetSeq1 set the first sequence to be compared. The second sequence to be compared is // not changed. // // SequenceMatcher computes and caches detailed information about the second @@ -141,7 +144,7 @@ func (m *SequenceMatcher) SetSeq1(a []string) { m.opCodes = nil } -// Set the second sequence to be compared. The first sequence to be compared is +// SetSeq2 set the second sequence to be compared. The first sequence to be compared is // not changed. func (m *SequenceMatcher) SetSeq2(b []string) { if &b == &m.b { @@ -167,12 +170,12 @@ func (m *SequenceMatcher) chainB() { m.bJunk = map[string]struct{}{} if m.IsJunk != nil { junk := m.bJunk - for s, _ := range b2j { + for s := range b2j { if m.IsJunk(s) { junk[s] = struct{}{} } } - for s, _ := range junk { + for s := range junk { delete(b2j, s) } } @@ -187,7 +190,7 @@ func (m *SequenceMatcher) chainB() { popular[s] = struct{}{} } } - for s, _ := range popular { + for s := range popular { delete(b2j, s) } } @@ -277,7 +280,7 @@ func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { for besti+bestsize < ahi && bestj+bestsize < bhi && !m.isBJunk(m.b[bestj+bestsize]) && m.a[besti+bestsize] == m.b[bestj+bestsize] { - bestsize += 1 + bestsize++ } // Now that we have a wholly interesting match (albeit possibly @@ -294,13 +297,13 @@ func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { for besti+bestsize < ahi && bestj+bestsize < bhi && m.isBJunk(m.b[bestj+bestsize]) && m.a[besti+bestsize] == m.b[bestj+bestsize] { - bestsize += 1 + bestsize++ } return Match{A: besti, B: bestj, Size: bestsize} } -// Return list of triples describing matching subsequences. +// GetMatchingBlocks return list of triples describing matching subsequences. // // Each triple is of the form (i, j, n), and means that // a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in @@ -364,7 +367,7 @@ func (m *SequenceMatcher) GetMatchingBlocks() []Match { return m.matchingBlocks } -// Return list of 5-tuples describing how to turn a into b. +// GetOpCodes return list of 5-tuples describing how to turn a into b. // // Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple // has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the @@ -415,7 +418,7 @@ func (m *SequenceMatcher) GetOpCodes() []OpCode { return m.opCodes } -// Isolate change clusters by eliminating ranges with no changes. +// GetGroupedOpCodes isolate change clusters by eliminating ranges with no changes. // // Return a generator of groups with up to n lines of context. // Each group is in the same format as returned by GetOpCodes(). @@ -425,7 +428,7 @@ func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { } codes := m.GetOpCodes() if len(codes) == 0 { - codes = []OpCode{OpCode{'e', 0, 1, 0, 1}} + codes = []OpCode{{'e', 0, 1, 0, 1}} } // Fixup leading and trailing groups if they show no changes. if codes[0].Tag == 'e' { @@ -460,7 +463,7 @@ func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { return groups } -// Return a measure of the sequences' similarity (float in [0,1]). +// Ratio return a measure of the sequences' similarity (float in [0,1]). // // Where T is the total number of elements in both sequences, and // M is the number of matches, this is 2.0*M / T. @@ -479,7 +482,7 @@ func (m *SequenceMatcher) Ratio() float64 { return calculateRatio(matches, len(m.a)+len(m.b)) } -// Return an upper bound on ratio() relatively quickly. +// QuickRatio return an upper bound on ratio() relatively quickly. // // This isn't defined beyond that it is an upper bound on .Ratio(), and // is faster to compute. @@ -505,13 +508,13 @@ func (m *SequenceMatcher) QuickRatio() float64 { } avail[s] = n - 1 if n > 0 { - matches += 1 + matches++ } } return calculateRatio(matches, len(m.a)+len(m.b)) } -// Return an upper bound on ratio() very quickly. +// RealQuickRatio return an upper bound on ratio() very quickly. // // This isn't defined beyond that it is an upper bound on .Ratio(), and // is faster to compute than either .Ratio() or .QuickRatio(). @@ -529,12 +532,12 @@ func formatRangeUnified(start, stop int) string { return fmt.Sprintf("%d", beginning) } if length == 0 { - beginning -= 1 // empty ranges begin at line just before the range + beginning-- // empty ranges begin at line just before the range } return fmt.Sprintf("%d,%d", beginning, length) } -// Unified diff parameters +// UnifiedDiff diff parameters type UnifiedDiff struct { A []string // First sequence lines FromFile string // First file name @@ -546,7 +549,7 @@ type UnifiedDiff struct { Context int // Number of context lines } -// Compare two sequences of lines; generate the delta as a unified diff. +// WriteUnifiedDiff compare two sequences of lines; generate the delta as a unified diff. // // Unified diffs are a compact way of showing line changes and a few // lines of context. The number of context lines is set by 'n' which @@ -647,11 +650,11 @@ func colorize(color, message string) string { return color + message + "\033[0m" } -// Like WriteUnifiedDiff but returns the diff a string. +// GetUnifiedDiffString like WriteUnifiedDiff but returns the diff a string. func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { w := &bytes.Buffer{} err := WriteUnifiedDiff(w, diff) - return string(w.Bytes()), err + return w.String(), err } // Convert range to the "ed" format. @@ -660,7 +663,7 @@ func formatRangeContext(start, stop int) string { beginning := start + 1 // lines start numbering with one length := stop - start if length == 0 { - beginning -= 1 // empty ranges begin at line just before the range + beginning-- // empty ranges begin at line just before the range } if length <= 1 { return fmt.Sprintf("%d", beginning) @@ -668,9 +671,10 @@ func formatRangeContext(start, stop int) string { return fmt.Sprintf("%d,%d", beginning, beginning+length-1) } +// ContextDiff is UnifiedDiff for managing context type ContextDiff UnifiedDiff -// Compare two sequences of lines; generate the delta as a context diff. +// WriteContextDiff compare two sequences of lines; generate the delta as a context diff. // // Context diffs are a compact way of showing line changes and a few // lines of context. The number of context lines is set by diff.Context @@ -772,14 +776,14 @@ func WriteContextDiff(writer io.Writer, diff ContextDiff) error { return diffErr } -// Like WriteContextDiff but returns the diff a string. +// GetContextDiffString like WriteContextDiff but returns the diff a string. func GetContextDiffString(diff ContextDiff) (string, error) { w := &bytes.Buffer{} err := WriteContextDiff(w, diff) - return string(w.Bytes()), err + return w.String(), err } -// Split a string on "\n" while preserving them. The output can be used +// SplitLines split a string on "\n" while preserving them. The output can be used // as input for UnifiedDiff and ContextDiff structures. func SplitLines(s string) []string { lines := strings.SplitAfter(s, "\n") diff --git a/difflib/difflib_test.go b/difflib/difflib_test.go index 5b52b5a..f8ff636 100644 --- a/difflib/difflib_test.go +++ b/difflib/difflib_test.go @@ -46,7 +46,7 @@ func TestGetOptCodes(t *testing.T) { fmt.Fprintf(w, "%s a[%d:%d], (%s) b[%d:%d] (%s)\n", string(op.Tag), op.I1, op.I2, a[op.I1:op.I2], op.J1, op.J2, b[op.J1:op.J2]) } - result := string(w.Bytes()) + result := w.String() expected := `d a[0:1], (q) b[0:0] () e a[1:3], (ab) b[0:2] (ab) r a[3:4], (x) b[2:3] (y) @@ -81,7 +81,7 @@ func TestGroupedOpCodes(t *testing.T) { op.I1, op.I2, op.J1, op.J2) } } - result := string(w.Bytes()) + result := w.String() expected := `group e, 5, 8, 5, 8 i, 8, 8, 8, 9 @@ -150,7 +150,7 @@ func TestWithAsciiBJunk(t *testing.T) { assertEqual(t, sm.bJunk, map[string]struct{}{" ": {}, "b": {}}) } -func TestSFBugsRatioForNullSeqn(t *testing.T) { +func TestSFBugsRatioForNullSeqN(t *testing.T) { sm := NewMatcher(nil, nil) assertEqual(t, sm.Ratio(), 1.0) assertEqual(t, sm.QuickRatio(), 1.0) @@ -235,7 +235,7 @@ func TestOutputFormatTabDelimiter(t *testing.T) { }) } -func TestOutputFormatNoTrailingTabOnEmptyFiledate(t *testing.T) { +func TestOutputFormatNoTrailingTabOnEmptyFileDate(t *testing.T) { diff := UnifiedDiff{ A: splitChars("one"), B: splitChars("two"), diff --git a/examples/echo/api_test.go b/examples/echo/api_test.go index 5d22470..1b3c372 100644 --- a/examples/echo/api_test.go +++ b/examples/echo/api_test.go @@ -4,21 +4,22 @@ import ( "net/http" "testing" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" + jsonpath "github.com/steinfletcher/apitest-jsonpath" ) func TestGetUserCookieMatching(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp()). Get("/user/1234"). Expect(t). - Cookies(apitest.NewCookie("CookieForAndy").Value("Andy")). + Cookies(spectest.NewCookie("CookieForAndy").Value("Andy")). Status(http.StatusOK). End() } func TestGetUserSuccess(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp()). Get("/user/1234"). Expect(t). @@ -28,7 +29,7 @@ func TestGetUserSuccess(t *testing.T) { } func TestGetUserSuccessJSONPath(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp()). Get("/user/1234"). Expect(t). @@ -38,7 +39,7 @@ func TestGetUserSuccessJSONPath(t *testing.T) { } func TestGetUserNotFound(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp()). Get("/user/1515"). Expect(t). diff --git a/examples/fiber/api_test.go b/examples/fiber/api_test.go index 29a5005..8673b20 100644 --- a/examples/fiber/api_test.go +++ b/examples/fiber/api_test.go @@ -5,23 +5,23 @@ import ( "net/http" "testing" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" "github.com/gofiber/fiber/v2" jsonpath "github.com/steinfletcher/apitest-jsonpath" ) func TestGetUserCookieMatching(t *testing.T) { - apitest.New(). + spectest.New(). HandlerFunc(FiberToHandlerFunc(newApp())). Get("/user/1234"). Expect(t). - Cookies(apitest.NewCookie("CookieForAndy").Value("Andy")). + Cookies(spectest.NewCookie("CookieForAndy").Value("Andy")). Status(http.StatusOK). End() } func TestGetUserSuccess(t *testing.T) { - apitest.New(). + spectest.New(). HandlerFunc(FiberToHandlerFunc(newApp())). Get("/user/1234"). Expect(t). @@ -31,7 +31,7 @@ func TestGetUserSuccess(t *testing.T) { } func TestGetUserSuccessJSONPath(t *testing.T) { - apitest.New(). + spectest.New(). HandlerFunc(FiberToHandlerFunc(newApp())). Get("/user/1234"). Expect(t). @@ -41,7 +41,7 @@ func TestGetUserSuccessJSONPath(t *testing.T) { } func TestGetUserNotFound(t *testing.T) { - apitest.New(). + spectest.New(). HandlerFunc(FiberToHandlerFunc(newApp())). Get("/user/1515"). Expect(t). diff --git a/examples/gin/api_test.go b/examples/gin/api_test.go index c790d6c..2aa15f0 100644 --- a/examples/gin/api_test.go +++ b/examples/gin/api_test.go @@ -4,15 +4,16 @@ import ( "net/http" "testing" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" + jsonpath "github.com/steinfletcher/apitest-jsonpath" ) func TestGetUserCookieMatching(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp().Router). Get("/user/1234"). Expect(t). - Cookies(apitest.NewCookie("TomsFavouriteDrink"). + Cookies(spectest.NewCookie("TomsFavouriteDrink"). Value("Beer"). Path("/")). Status(http.StatusOK). @@ -20,7 +21,7 @@ func TestGetUserCookieMatching(t *testing.T) { } func TestGetUserSuccess(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp().Router). Get("/user/1234"). Expect(t). @@ -30,7 +31,7 @@ func TestGetUserSuccess(t *testing.T) { } func TestGetUserSuccessJSONPath(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp().Router). Get("/user/1234"). Expect(t). @@ -40,7 +41,7 @@ func TestGetUserSuccessJSONPath(t *testing.T) { } func TestGetUserNotFound(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp().Router). Get("/user/1515"). Expect(t). diff --git a/examples/ginkgo/server_test.go b/examples/ginkgo/server_test.go index 8a8df92..2aff7fe 100644 --- a/examples/ginkgo/server_test.go +++ b/examples/ginkgo/server_test.go @@ -3,7 +3,7 @@ package server_test import ( "net/http" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" "github.com/gorilla/mux" . "github.com/onsi/ginkgo" jsonpath "github.com/steinfletcher/apitest-jsonpath" @@ -24,11 +24,11 @@ var _ = Describe("Ginkgo/Server", func() { Context("Successful CookieMatching", func() { It("cookies should be set correctly", func() { - apitest.New(). + spectest.New(). Handler(router). Get("/user/1234"). Expect(t). - Cookies(apitest.NewCookie("TomsFavouriteDrink"). + Cookies(spectest.NewCookie("TomsFavouriteDrink"). Value("Beer"). Path("/")). Status(http.StatusOK). @@ -38,7 +38,7 @@ var _ = Describe("Ginkgo/Server", func() { Context("Successful GetUser", func() { It("Get User body should return desired value", func() { - apitest.New(). + spectest.New(). Handler(router). Get("/user/1234"). Expect(t). @@ -48,7 +48,7 @@ var _ = Describe("Ginkgo/Server", func() { }) It("Get User jsonpath should return desired value", func() { - apitest.New(). + spectest.New(). Handler(router). Get("/user/1234"). Expect(t). @@ -60,7 +60,7 @@ var _ = Describe("Ginkgo/Server", func() { Context("Unsuccessful GetUser", func() { It("User not found error should be raised", func() { - apitest.New(). + spectest.New(). Handler(router). Get("/user/1515"). Expect(t). diff --git a/examples/gorilla/api_test.go b/examples/gorilla/api_test.go index c790d6c..2aa15f0 100644 --- a/examples/gorilla/api_test.go +++ b/examples/gorilla/api_test.go @@ -4,15 +4,16 @@ import ( "net/http" "testing" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" + jsonpath "github.com/steinfletcher/apitest-jsonpath" ) func TestGetUserCookieMatching(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp().Router). Get("/user/1234"). Expect(t). - Cookies(apitest.NewCookie("TomsFavouriteDrink"). + Cookies(spectest.NewCookie("TomsFavouriteDrink"). Value("Beer"). Path("/")). Status(http.StatusOK). @@ -20,7 +21,7 @@ func TestGetUserCookieMatching(t *testing.T) { } func TestGetUserSuccess(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp().Router). Get("/user/1234"). Expect(t). @@ -30,7 +31,7 @@ func TestGetUserSuccess(t *testing.T) { } func TestGetUserSuccessJSONPath(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp().Router). Get("/user/1234"). Expect(t). @@ -40,7 +41,7 @@ func TestGetUserSuccessJSONPath(t *testing.T) { } func TestGetUserNotFound(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp().Router). Get("/user/1515"). Expect(t). diff --git a/examples/graphql/api_test.go b/examples/graphql/api_test.go index 7974bc6..5fe420f 100644 --- a/examples/graphql/api_test.go +++ b/examples/graphql/api_test.go @@ -4,13 +4,13 @@ import ( "net/http" "testing" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" jsonpath "github.com/steinfletcher/apitest-jsonpath" "github.com/steinfletcher/apitest/examples/graphql/graph" ) func TestQueryEmpty(t *testing.T) { - apitest.New(). + spectest.New(). Handler(graph.NewHandler()). Post("/query"). GraphQLQuery(`query { @@ -35,7 +35,7 @@ func TestQueryEmpty(t *testing.T) { func TestQueryWithTodo(t *testing.T) { handler := graph.NewHandler() - apitest.New(). + spectest.New(). Handler(handler). Post("/query"). JSON(`{"query": "mutation { createTodo(input:{text:\"todo\", userId:\"4\"}) { user { id } text done } }"}`). @@ -44,7 +44,7 @@ func TestQueryWithTodo(t *testing.T) { Assert(jsonpath.Equal("$.data.createTodo.user.id", "4")). End() - apitest.New(). + spectest.New(). Handler(handler). Post("/query"). GraphQLQuery("query { todos { text done user { name } } }"). diff --git a/examples/httprouter/api_test.go b/examples/httprouter/api_test.go index 06ac96c..fed2433 100644 --- a/examples/httprouter/api_test.go +++ b/examples/httprouter/api_test.go @@ -4,22 +4,22 @@ import ( "net/http" "testing" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" jsonpath "github.com/steinfletcher/apitest-jsonpath" ) func TestGetUserCookieMatching(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newRouter()). Get("/user/1234"). Expect(t). - Cookies(apitest.NewCookie("CookieForAndy").Value("Andy")). + Cookies(spectest.NewCookie("CookieForAndy").Value("Andy")). Status(http.StatusOK). End() } func TestGetUserSuccess(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newRouter()). Get("/user/1234"). Expect(t). @@ -29,7 +29,7 @@ func TestGetUserSuccess(t *testing.T) { } func TestGetUserSuccessJSONPath(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newRouter()). Get("/user/1234"). Expect(t). @@ -39,7 +39,7 @@ func TestGetUserSuccessJSONPath(t *testing.T) { } func TestGetUserNotFound(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newRouter()). Get("/user/1515"). Expect(t). diff --git a/examples/iris/api_test.go b/examples/iris/api_test.go index 9133748..8d6885e 100644 --- a/examples/iris/api_test.go +++ b/examples/iris/api_test.go @@ -4,15 +4,16 @@ import ( "net/http" "testing" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" + jsonpath "github.com/steinfletcher/apitest-jsonpath" ) func TestGetUserCookieMatching(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp().iris.Router). Get("/user/1234"). Expect(t). - Cookies(apitest.NewCookie("TomsFavouriteDrink"). + Cookies(spectest.NewCookie("TomsFavouriteDrink"). Value("Beer"). Path("/")). Status(http.StatusOK). @@ -20,7 +21,7 @@ func TestGetUserCookieMatching(t *testing.T) { } func TestGetUserSuccess(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp().iris.Router). Get("/user/1234"). Expect(t). @@ -30,7 +31,7 @@ func TestGetUserSuccess(t *testing.T) { } func TestGetUserSuccessJSONPath(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp().iris.Router). Get("/user/1234"). Expect(t). @@ -40,7 +41,7 @@ func TestGetUserSuccessJSONPath(t *testing.T) { } func TestGetUserNotFound(t *testing.T) { - apitest.New(). + spectest.New(). Handler(newApp().iris.Router). Get("/user/1515"). Expect(t). diff --git a/examples/mocks/api_test.go b/examples/mocks/api_test.go index c83615a..d59266c 100644 --- a/examples/mocks/api_test.go +++ b/examples/mocks/api_test.go @@ -5,11 +5,11 @@ import ( "net/http" "testing" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" ) func TestGetUserSuccess(t *testing.T) { - apitest.New(). + spectest.New(). Mocks(getPreferencesMock, getUserMock). Handler(newApp().Router). Get("/user"). @@ -19,9 +19,9 @@ func TestGetUserSuccess(t *testing.T) { End() } -var getPreferencesMock = apitest.NewMock(). +var getPreferencesMock = spectest.NewMock(). Get("/preferences/12345"). - AddMatcher(func(r *http.Request, mr *apitest.MockRequest) error { + AddMatcher(func(r *http.Request, mr *spectest.MockRequest) error { // Custom matching func for URL Scheme if r.URL.Scheme != "http" { return errors.New("request did not have 'http' scheme") @@ -33,7 +33,7 @@ var getPreferencesMock = apitest.NewMock(). Status(http.StatusOK). End() -var getUserMock = apitest.NewMock(). +var getUserMock = spectest.NewMock(). Get("/user/12345"). RespondWith(). Body(`{"name": "jon", "id": "1234"}`). diff --git a/examples/sequence-diagrams-with-mysql-database/Makefile b/examples/sequence-diagrams-with-mysql-database/Makefile index b9d5bfa..8bd6e20 100644 --- a/examples/sequence-diagrams-with-mysql-database/Makefile +++ b/examples/sequence-diagrams-with-mysql-database/Makefile @@ -1,15 +1,15 @@ .PHONY: mysql-dev test mysql-dev: - docker stop apitest_mysql || true && docker rm apitest_mysql || true + docker stop spectest_mysql || true && docker rm spectest_mysql || true docker run -d \ -e MYSQL_ROOT_PASSWORD=mysql \ -e MYSQL_PASSWORD=mysql \ -e MYSQL_USER=mysql \ - -e MYSQL_DATABASE=apitest \ + -e MYSQL_DATABASE=spectest \ -p 3306:3306 \ --name apitest_mysql \ mysql:8.0 test: - MYSQL_DSN="mysql:mysql@/apitest" go test ./... -v + MYSQL_DSN="mysql:mysql@/spectest" go test ./... -v diff --git a/examples/sequence-diagrams-with-mysql-database/api_test.go b/examples/sequence-diagrams-with-mysql-database/api_test.go index 13fa4d8..59aa966 100644 --- a/examples/sequence-diagrams-with-mysql-database/api_test.go +++ b/examples/sequence-diagrams-with-mysql-database/api_test.go @@ -7,22 +7,22 @@ import ( "os" "testing" - apitest "github.com/go-spectest/spectest" - apitestdb "github.com/go-spectest/spectest/x/db" + "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest/x/db" "github.com/jmoiron/sqlx" uuid "github.com/satori/go.uuid" ) // This test requires a mysql database to run -var recorder *apitest.Recorder +var recorder *spectest.Recorder func init() { - recorder = apitest.NewTestRecorder() + recorder = spectest.NewTestRecorder() // Wrap your database driver of choice with a recorder // and register it so you can use it later - wrappedDriver := apitestdb.WrapWithRecorder("mysql", recorder) + wrappedDriver := db.WrapWithRecorder("mysql", recorder) sql.Register("wrappedMysql", wrappedDriver) } @@ -77,8 +77,8 @@ func TestPostUserWithDefaultReportFormatter(t *testing.T) { End() } -func getUserMock(username string) *apitest.Mock { - return apitest.NewMock(). +func getUserMock(username string) *spectest.Mock { + return spectest.NewMock(). Get("http://users/api/user"). Query("id", username). RespondWith(). @@ -87,8 +87,8 @@ func getUserMock(username string) *apitest.Mock { End() } -func postUserMock(username string) *apitest.Mock { - return apitest.NewMock(). +func postUserMock(username string) *spectest.Mock { + return spectest.NewMock(). Post("http://users/api/user"). Body(fmt.Sprintf(`{"name": "%s"}`, username)). RespondWith(). @@ -96,7 +96,7 @@ func postUserMock(username string) *apitest.Mock { End() } -func apiTest(name string) *apitest.APITest { +func apiTest(name string) *spectest.APITest { dsn := os.Getenv("MYSQL_DSN") // Connect using the previously registered driver @@ -123,8 +123,8 @@ func apiTest(name string) *apitest.APITest { app := newApp(testDB) - return apitest.New(name). + return spectest.New(name). Recorder(recorder). - Report(apitest.SequenceDiagram()). + Report(spectest.SequenceDiagram()). Handler(app.Router) } diff --git a/examples/sequence-diagrams-with-postgres-database/Makefile b/examples/sequence-diagrams-with-postgres-database/Makefile index 3392803..2148ba0 100644 --- a/examples/sequence-diagrams-with-postgres-database/Makefile +++ b/examples/sequence-diagrams-with-postgres-database/Makefile @@ -1,8 +1,8 @@ .PHONY: postgres-dev test postgres-dev: - docker stop apitest_postgres || true && docker rm apitest_postgres || true - docker run -d -e POSTGRES_PASSWORD=postgres -e POSTGRES_USER=postgres -e POSTGRES_DB=apitest -p 5432:5432 --name apitest_postgres postgres:9.6 + docker stop spectest_postgres || true && docker rm spectest_postgres || true + docker run -d -e POSTGRES_PASSWORD=postgres -e POSTGRES_USER=postgres -e POSTGRES_DB=spectest -p 5432:5432 --name spectest_postgres postgres:9.6 test: - POSTGRES_DSN="host=localhost port=5432 user=postgres password=postgres dbname=apitest sslmode=disable" go test ./... -v + POSTGRES_DSN="host=localhost port=5432 user=postgres password=postgres dbname=spectest sslmode=disable" go test ./... -v diff --git a/examples/sequence-diagrams-with-postgres-database/api_test.go b/examples/sequence-diagrams-with-postgres-database/api_test.go index c742d75..56ce0c5 100644 --- a/examples/sequence-diagrams-with-postgres-database/api_test.go +++ b/examples/sequence-diagrams-with-postgres-database/api_test.go @@ -6,7 +6,7 @@ import ( "os" "testing" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" "github.com/go-spectest/spectest/examples/sequence-diagrams-with-postgres-database/test" _ "github.com/go-spectest/spectest/examples/sequence-diagrams-with-postgres-database/test" "github.com/jmoiron/sqlx" @@ -24,7 +24,7 @@ func TestGetUserWithDefaultReportFormatter(t *testing.T) { db.MustExec(q, username, true) }) - apiTest("gets the user"). + spectest("gets the user"). Mocks(getUserMock(username)). Get("/user"). Query("name", username). @@ -44,7 +44,7 @@ func TestPostUserWithDefaultReportFormatter(t *testing.T) { db.MustExec(q, username, true) }) - apiTest("creates a user"). + spectest("creates a user"). Mocks(postUserMock(username)). Post("/user"). Body(fmt.Sprintf(`{"name": "%s", "is_contactable": true}`, username)). @@ -54,8 +54,8 @@ func TestPostUserWithDefaultReportFormatter(t *testing.T) { End() } -func getUserMock(username string) *apitest.Mock { - return apitest.NewMock(). +func getUserMock(username string) *spectest.Mock { + return spectest.NewMock(). Get("http://users/api/user"). Query("id", username). RespondWith(). @@ -64,8 +64,8 @@ func getUserMock(username string) *apitest.Mock { End() } -func postUserMock(username string) *apitest.Mock { - return apitest.NewMock(). +func postUserMock(username string) *spectest.Mock { + return spectest.NewMock(). Post("http://users/api/user"). Body(fmt.Sprintf(`{"name": "%s"}`, username)). RespondWith(). @@ -73,11 +73,11 @@ func postUserMock(username string) *apitest.Mock { End() } -func apiTest(name string) *apitest.APITest { +func apiTest(name string) *spectest.APITest { app := newApp(test.DBConnect()) - return apitest.New(name). + return spectest.New(name). Recorder(test.Recorder). - Report(apitest.SequenceDiagram()). + Report(spectest.SequenceDiagram()). Handler(app.Router) } diff --git a/examples/sequence-diagrams-with-postgres-database/test/test_support.go b/examples/sequence-diagrams-with-postgres-database/test/test_support.go index 648238f..ac45280 100644 --- a/examples/sequence-diagrams-with-postgres-database/test/test_support.go +++ b/examples/sequence-diagrams-with-postgres-database/test/test_support.go @@ -3,19 +3,19 @@ package test import ( "database/sql" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" apitestdb "github.com/go-spectest/spectest/x/db" "github.com/jmoiron/sqlx" "github.com/pressly/goose" ) -const dsn = "host=localhost port=5432 user=postgres password=postgres dbname=apitest sslmode=disable" +const dsn = "host=localhost port=5432 user=postgres password=postgres dbname=spectest sslmode=disable" // Recorder is a generic recorder to be reused -var Recorder *apitest.Recorder +var Recorder *spectest.Recorder func init() { - Recorder = apitest.NewTestRecorder() + Recorder = spectest.NewTestRecorder() // Wrap your database driver of choice with a recorder // and register it so you can use it later diff --git a/examples/sequence-diagrams-with-sqlite-database/api_test.go b/examples/sequence-diagrams-with-sqlite-database/api_test.go index 8cd653a..e08375c 100644 --- a/examples/sequence-diagrams-with-sqlite-database/api_test.go +++ b/examples/sequence-diagrams-with-sqlite-database/api_test.go @@ -7,20 +7,20 @@ import ( "os" "testing" - apitest "github.com/go-spectest/spectest" - apitestdb "github.com/go-spectest/spectest/x/db" + "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest/x/db" "github.com/jmoiron/sqlx" uuid "github.com/satori/go.uuid" ) -var recorder *apitest.Recorder +var recorder *spectest.Recorder func init() { - recorder = apitest.NewTestRecorder() + recorder = spectest.NewTestRecorder() // Wrap your database driver of choice with a recorder // and register it so you can use it later - wrappedDriver := apitestdb.WrapWithRecorder("sqlite3", recorder) + wrappedDriver := db.WrapWithRecorder("sqlite3", recorder) sql.Register("wrappedSqlite", wrappedDriver) } @@ -72,8 +72,8 @@ func TestPostUserWithDefaultReportFormatter(t *testing.T) { End() } -func getUserMock(username string) *apitest.Mock { - return apitest.NewMock(). +func getUserMock(username string) *spectest.Mock { + return spectest.NewMock(). Get("http://users/api/user"). Query("id", username). RespondWith(). @@ -82,8 +82,8 @@ func getUserMock(username string) *apitest.Mock { End() } -func postUserMock(username string) *apitest.Mock { - return apitest.NewMock(). +func postUserMock(username string) *spectest.Mock { + return spectest.NewMock(). Post("http://users/api/user"). Body(fmt.Sprintf(`{"name": "%s"}`, username)). RespondWith(). @@ -91,7 +91,7 @@ func postUserMock(username string) *apitest.Mock { End() } -func apiTest(name string) *apitest.APITest { +func apiTest(name string) *spectest.APITest { dsn := os.Getenv("SQLITE_DSN") // Connect using the previously registered driver @@ -102,8 +102,8 @@ func apiTest(name string) *apitest.APITest { app := newApp(testDB) - return apitest.New(name). + return spectest.New(name). Recorder(recorder). - Report(apitest.SequenceDiagram()). + Report(spectest.SequenceDiagram()). Handler(app.Router) } diff --git a/examples/sequence-diagrams/api_test.go b/examples/sequence-diagrams/api_test.go index 4580e2f..f4220db 100644 --- a/examples/sequence-diagrams/api_test.go +++ b/examples/sequence-diagrams/api_test.go @@ -4,12 +4,12 @@ import ( "net/http" "testing" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" ) func TestGetUserWithDefaultReportFormatter(t *testing.T) { - apitest.New("gets the user 1"). - Report(apitest.SequenceDiagram()). + spectest.New("gets the user 1"). + Report(spectest.SequenceDiagram()). Meta(map[string]interface{}{"host": "user-service"}). Mocks(getPreferencesMock, getUserMock). Handler(newApp().Router). @@ -23,9 +23,9 @@ func TestGetUserWithDefaultReportFormatter(t *testing.T) { } func TestGetUserWithDefaultReportFormatterOverridingPath(t *testing.T) { - apitest.New("gets the user 2"). + spectest.New("gets the user 2"). Meta(map[string]interface{}{"host": "user-service"}). - Report(apitest.SequenceDiagram(".sequence-diagrams")). + Report(spectest.SequenceDiagram(".sequence-diagrams")). Mocks(getPreferencesMock, getUserMock). Handler(newApp().Router). Post("/user/search"). @@ -37,14 +37,14 @@ func TestGetUserWithDefaultReportFormatterOverridingPath(t *testing.T) { End() } -var getPreferencesMock = apitest.NewMock(). +var getPreferencesMock = spectest.NewMock(). Get("http://preferences/api/preferences/12345"). RespondWith(). Body(`{"is_contactable": true}`). Status(http.StatusOK). End() -var getUserMock = apitest.NewMock(). +var getUserMock = spectest.NewMock(). Get("http://users/api/user/12345"). RespondWith(). Body(`{"name": "jon", "id": "1234"}`). diff --git a/mocks.go b/mocks.go index cebecfe..72025d9 100644 --- a/mocks.go +++ b/mocks.go @@ -579,9 +579,7 @@ func (r *MockRequest) QueryParams(queryParams map[string]string) *MockRequest { // QueryCollection configures the mock request to match a number of repeating query params, e.g. ?a=1&a=2&a=3 func (r *MockRequest) QueryCollection(queryParams map[string][]string) *MockRequest { for k, v := range queryParams { - for _, val := range v { - r.query[k] = append(r.query[k], val) - } + r.query[k] = append(r.query[k], v...) } return r } diff --git a/mocks/verifier.go b/mocks/verifier.go index aebbb99..bd6a0ab 100644 --- a/mocks/verifier.go +++ b/mocks/verifier.go @@ -1,75 +1,76 @@ package mocks import ( - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" ) -var _ apitest.Verifier = MockVerifier{} +var _ spectest.Verifier = &MockVerifier{} -// MockVerifier is a mock of the Verifier interface that is used in tests of apitest +// MockVerifier is a mock of the Verifier interface that is used in tests of spectest type MockVerifier struct { - EqualFn func(t apitest.TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool + EqualFn func(t spectest.TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool EqualInvoked bool - TrueFn func(t apitest.TestingT, val bool, msgAndArgs ...interface{}) bool + TrueFn func(t spectest.TestingT, val bool, msgAndArgs ...interface{}) bool TrueInvoked bool - JSONEqFn func(t apitest.TestingT, expected string, actual string, msgAndArgs ...interface{}) bool + JSONEqFn func(t spectest.TestingT, expected string, actual string, msgAndArgs ...interface{}) bool JSONEqInvoked bool - FailFn func(t apitest.TestingT, failureMessage string, msgAndArgs ...interface{}) bool + FailFn func(t spectest.TestingT, failureMessage string, msgAndArgs ...interface{}) bool FailInvoked bool - NoErrorFn func(t apitest.TestingT, err error, msgAndArgs ...interface{}) bool + NoErrorFn func(t spectest.TestingT, err error, msgAndArgs ...interface{}) bool NoErrorInvoked bool } -func NewVerifier() MockVerifier { - return MockVerifier{ - EqualFn: func(t apitest.TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { +// NewVerifier creates a new instance of the MockVerifier +func NewVerifier() *MockVerifier { + return &MockVerifier{ + EqualFn: func(t spectest.TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { return true }, - JSONEqFn: func(t apitest.TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { + JSONEqFn: func(t spectest.TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { return true }, - FailFn: func(t apitest.TestingT, failureMessage string, msgAndArgs ...interface{}) bool { + FailFn: func(t spectest.TestingT, failureMessage string, msgAndArgs ...interface{}) bool { return true }, - NoErrorFn: func(t apitest.TestingT, err error, msgAndArgs ...interface{}) bool { + NoErrorFn: func(t spectest.TestingT, err error, msgAndArgs ...interface{}) bool { return true }, - TrueFn: func(t apitest.TestingT, val bool, msgAndArgs ...interface{}) bool { + TrueFn: func(t spectest.TestingT, val bool, msgAndArgs ...interface{}) bool { return true }, } } // Equal mocks the Equal method of the Verifier -func (m MockVerifier) Equal(t apitest.TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { +func (m *MockVerifier) Equal(t spectest.TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { m.EqualInvoked = true return m.EqualFn(t, expected, actual, msgAndArgs) } // True mocks the Equal method of the Verifier -func (m MockVerifier) True(t apitest.TestingT, val bool, msgAndArgs ...interface{}) bool { +func (m *MockVerifier) True(t spectest.TestingT, val bool, msgAndArgs ...interface{}) bool { m.TrueInvoked = true return m.TrueFn(t, val, msgAndArgs) } // JSONEq mocks the JSONEq method of the Verifier -func (m MockVerifier) JSONEq(t apitest.TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { +func (m *MockVerifier) JSONEq(t spectest.TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { m.JSONEqInvoked = true return m.JSONEqFn(t, expected, actual, msgAndArgs) } // Fail mocks the Fail method of the Verifier -func (m MockVerifier) Fail(t apitest.TestingT, failureMessage string, msgAndArgs ...interface{}) bool { +func (m *MockVerifier) Fail(t spectest.TestingT, failureMessage string, msgAndArgs ...interface{}) bool { m.FailInvoked = true return m.FailFn(t, failureMessage, msgAndArgs) } // NoError asserts that a function returned no error -func (m MockVerifier) NoError(t apitest.TestingT, err error, msgAndArgs ...interface{}) bool { +func (m *MockVerifier) NoError(t spectest.TestingT, err error, msgAndArgs ...interface{}) bool { m.NoErrorInvoked = true return m.NoErrorFn(t, err, msgAndArgs) } diff --git a/mocks_test.go b/mocks_test.go index 72655f9..cc3ce5d 100644 --- a/mocks_test.go +++ b/mocks_test.go @@ -115,22 +115,22 @@ func TestMocksNewEmptyUnmatchedMockErrorExpectedErrorsString(t *testing.T) { func TestMocksHostMatcher(t *testing.T) { tests := map[string]struct { request *http.Request - mockUrl string + mockURL string expectedError error }{ "matching": { request: httptest.NewRequest(http.MethodGet, "http://test.com", nil), - mockUrl: "https://test.com", + mockURL: "https://test.com", expectedError: nil, }, "not matching": { request: httptest.NewRequest(http.MethodGet, "https://test.com", nil), - mockUrl: "https://testa.com", + mockURL: "https://testa.com", expectedError: errors.New("received host test.com did not match mock host testa.com"), }, "no expected host": { request: httptest.NewRequest(http.MethodGet, "https://test.com", nil), - mockUrl: "", + mockURL: "", expectedError: nil, }, "matching using URL host": { @@ -138,13 +138,13 @@ func TestMocksHostMatcher(t *testing.T) { Host: "test.com", Path: "/", }}, - mockUrl: "https://test.com", + mockURL: "https://test.com", expectedError: nil, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { - matchError := hostMatcher(test.request, NewMock().Get(test.mockUrl)) + matchError := hostMatcher(test.request, NewMock().Get(test.mockURL)) assert.Equal(t, test.expectedError, matchError) }) } diff --git a/spectest.code-workspace b/spectest.code-workspace new file mode 100644 index 0000000..48ed0d5 --- /dev/null +++ b/spectest.code-workspace @@ -0,0 +1,75 @@ +{ + "folders": [ + { + "path": "." + } + ], + "settings": { + "cSpell.words": [ + "abycdf", + "acab", + "apitest", + "authtoken", + "bcde", + "besti", + "bestj", + "bestsize", + "Bodyf", + "Deletef", + "difflib", + "formdata", + "fromfile", + "fromfiledate", + "fsadg", + "Getf", + "Headerkey", + "kddejong", + "kfiufhtne", + "lineterm", + "multisets", + "newj", + "nolint", + "ntest", + "Obershelp", + "octocov", + "Patchf", + "pdsanjdna", + "Postf", + "Putf", + "qabxcd", + "Ratcliff", + "readlines", + "Seqs", + "shellcheck", + "spectest", + "steinfletcher", + "timonwong", + "todos", + "tofile", + "tofiledate", + "unidiff", + "windiff", + "writelines" + ], + "cfnLint.path": "cfn-lint", + "cfnLint.overrideSpecPath": ".github/cfn-resource-specification.json", + "editor.formatOnSave": true, + "[json]": { + "editor.defaultFormatter": "vscode.json-language-features", + "editor.detectIndentation": false, + "editor.insertSpaces": true, + }, + "go.testTimeout": "300s", + "files.watcherExclude": { + "**/target": true + }, + }, + "extensions": { + "recommendations": [ + "timonwong.shellcheck", + "golang.go", + "streetsidesoftware.code-spell-checker", + "kddejong.vscode-cfn-lint", + ] + } +} diff --git a/spectest.go b/spectest.go index 12fbab8..080cad4 100644 --- a/spectest.go +++ b/spectest.go @@ -58,18 +58,6 @@ type APITest struct { finished time.Time } -// InboundRequest used to wrap the incoming request with a timestamp -type InboundRequest struct { - request *http.Request - timestamp time.Time -} - -// FinalResponse used to wrap the final response with a timestamp -type FinalResponse struct { - response *http.Response - timestamp time.Time -} - // Observe will be called by with the request and response on completion type Observe func(*http.Response, *http.Request, *APITest) @@ -102,12 +90,12 @@ func New(name ...string) *APITest { return apiTest } -// Handler is a convenience method for creating a new apitest with a handler +// Handler is a convenience method for creating a new spectest with a handler func Handler(handler http.Handler) *APITest { return New().Handler(handler) } -// HandlerFunc is a convenience method for creating a new apitest with a handler func +// HandlerFunc is a convenience method for creating a new spectest with a handler func func HandlerFunc(handlerFunc http.HandlerFunc) *APITest { return New().HandlerFunc(handlerFunc) } @@ -129,7 +117,7 @@ func (a *APITest) EnableMockResponseDelay() *APITest { return a } -// Debug logs to the console the http wire representation of all http interactions that are intercepted by apitest. This includes the inbound request to the application under test, the response returned by the application and any interactions that are intercepted by the mock server. +// Debug logs to the console the http wire representation of all http interactions that are intercepted by spectest. This includes the inbound request to the application under test, the response returned by the application and any interactions that are intercepted by the mock server. func (a *APITest) Debug() *APITest { a.debugEnabled = true return a @@ -679,7 +667,7 @@ func (r *Response) End() Result { defer func() { if apiTest.debugEnabled { apiTest.finished = time.Now() - fmt.Println(fmt.Sprintf("Duration: %s\n", apiTest.finished.Sub(apiTest.started))) + fmt.Printf("Duration: %s\n", apiTest.finished.Sub(apiTest.started)) } }() @@ -697,7 +685,7 @@ func (r *Response) End() Result { var unmatchedMocks []UnmatchedMock for _, m := range r.apiTest.mocks { - if m.isUsed == false { + if !m.isUsed { unmatchedMocks = append(unmatchedMocks, UnmatchedMock{ URL: *m.request.url, }) @@ -898,7 +886,7 @@ func (r *Response) runTest() *http.Response { func (a *APITest) assertMocks() { for _, mock := range a.mocks { - if mock.isUsed == false && mock.timesSet { + if !mock.isUsed && mock.timesSet { a.verifier.Fail(a.t, "mock was not invoked expected times", failureMessageArgs{Name: a.name}) } } diff --git a/spectest_test.go b/spectest_test.go index e122177..9fed76b 100644 --- a/spectest_test.go +++ b/spectest_test.go @@ -15,12 +15,12 @@ import ( "testing" "time" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" "github.com/go-spectest/spectest/mocks" ) func TestApiTestResponseBody(t *testing.T) { - apitest.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + spectest.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"id": "1234", "name": "Andy"}`)) w.WriteHeader(http.StatusOK) }). @@ -48,7 +48,7 @@ func TestApiTestHttpRequest(t *testing.T) { request := httptest.NewRequest(http.MethodGet, "/hello", strings.NewReader("hello")) request.Header.Set("key", "val") - apitest.Handler(handler). + spectest.Handler(handler). HTTPRequest(request). Expect(t). Status(http.StatusOK). @@ -70,7 +70,7 @@ func TestApiTestAddsJSONBodyToRequest(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.Handler(handler). + spectest.Handler(handler). Post("/hello"). Body(`{"a": 12345}`). Header("Content-Type", "application/json"). @@ -94,7 +94,7 @@ func TestApiTestAddsJSONBodyToRequestSupportsFormatter(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Post("/hello"). Bodyf(`{"a": %d}`, 12345). @@ -105,7 +105,7 @@ func TestApiTestAddsJSONBodyToRequestSupportsFormatter(t *testing.T) { } func TestApiTestRequestURLFormat(t *testing.T) { - apitest.New(). + spectest.New(). HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) assert.Equal(t, "/user/1234", r.URL.Path) @@ -115,7 +115,7 @@ func TestApiTestRequestURLFormat(t *testing.T) { Status(http.StatusOK). End() - apitest.New(). + spectest.New(). HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) assert.Equal(t, "/user/1234", r.URL.Path) @@ -125,7 +125,7 @@ func TestApiTestRequestURLFormat(t *testing.T) { Status(http.StatusOK). End() - apitest.New(). + spectest.New(). HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) assert.Equal(t, "/user/1234", r.URL.Path) @@ -135,7 +135,7 @@ func TestApiTestRequestURLFormat(t *testing.T) { Status(http.StatusOK). End() - apitest.New(). + spectest.New(). HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) assert.Equal(t, "/user/1234", r.URL.Path) @@ -145,7 +145,7 @@ func TestApiTestRequestURLFormat(t *testing.T) { Status(http.StatusOK). End() - apitest.New(). + spectest.New(). HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) assert.Equal(t, "/user/1234", r.URL.Path) @@ -155,7 +155,7 @@ func TestApiTestRequestURLFormat(t *testing.T) { Status(http.StatusOK). End() - apitest.New(). + spectest.New(). HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) assert.Equal(t, "/user/1234", r.URL.Path) @@ -201,7 +201,7 @@ func TestApiTestJSONBody(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Post("/hello"). JSON(test.body). @@ -227,7 +227,7 @@ func TestApiTestAddsJSONBodyToRequestUsingJSON(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Post("/hello"). JSON(`{"a": 12345}`). @@ -247,7 +247,7 @@ func TestApiTestAddsTextBodyToRequest(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Put("/hello"). Body(`hello`). @@ -259,14 +259,14 @@ func TestApiTestAddsTextBodyToRequest(t *testing.T) { func TestApiTestAddsQueryParamsToRequest(t *testing.T) { handler := http.NewServeMux() handler.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { - if "b" != r.URL.Query().Get("a") { + if r.URL.Query().Get("a") != "b" { w.WriteHeader(http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Get("/hello"). QueryParams(map[string]string{"a": "b"}). @@ -278,14 +278,14 @@ func TestApiTestAddsQueryParamsToRequest(t *testing.T) { func TestApiTestAddsQueryParamCollectionToRequest(t *testing.T) { handler := http.NewServeMux() handler.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { - if "a=b&a=c&a=d&e=f" != r.URL.RawQuery { + if r.URL.RawQuery != "a=b&a=c&a=d&e=f" { w.WriteHeader(http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Get("/hello"). QueryCollection(map[string][]string{"a": {"b", "c", "d"}}). @@ -298,14 +298,14 @@ func TestApiTestAddsQueryParamCollectionToRequest(t *testing.T) { func TestApiTestAddsQueryParamCollectionToRequestHandlesEmpty(t *testing.T) { handler := http.NewServeMux() handler.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { - if "e=f" != r.URL.RawQuery { + if r.URL.RawQuery != "e=f" { w.WriteHeader(http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Get("/hello"). QueryCollection(map[string][]string{}). @@ -326,7 +326,7 @@ func TestApiTestCanCombineQueryParamMethods(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Get("/hello"). Query("a", "9"). @@ -349,7 +349,7 @@ func TestApiTestAddsHeadersToRequest(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Delete("/hello"). Headers(map[string]string{"Authorization": "12345"}). @@ -369,7 +369,7 @@ func TestApiTestAddsContentTypeHeaderToRequest(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Post("/hello"). ContentType("application/x-www-form-urlencoded"). @@ -393,12 +393,12 @@ func TestApiTestAddsCookiesToRequest(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Method(http.MethodGet). URL("/hello"). Cookie("Cookie", "Nom"). - Cookies(apitest.NewCookie("Cookie1").Value("Yummy")). + Cookies(spectest.NewCookie("Cookie1").Value("Yummy")). Expect(t). Status(http.StatusOK). End() @@ -419,7 +419,7 @@ func TestApiTestAddsBasicAuthToRequest(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New("some test name"). + spectest.New("some test name"). Handler(handler). Get("/hello"). BasicAuth("username", "password"). @@ -441,7 +441,7 @@ func TestApiTestAddsTimedOutContextToRequest(t *testing.T) { timeoutCtx, cancel := context.WithTimeout(context.Background(), time.Nanosecond*1) defer cancel() - apitest.New("test with timed out context"). + spectest.New("test with timed out context"). Handler(handler). Get("/hello"). WithContext(timeoutCtx). @@ -463,7 +463,7 @@ func TestApiTestAddsCancelledContextToRequest(t *testing.T) { cancelCtx, cancel := context.WithCancel(context.Background()) cancel() - apitest.New("test with canceled context"). + spectest.New("test with canceled context"). Handler(handler). Get("/hello"). WithContext(cancelCtx). @@ -473,19 +473,19 @@ func TestApiTestAddsCancelledContextToRequest(t *testing.T) { } func TestApiTestGraphQLQuery(t *testing.T) { - apitest.New(). + spectest.New(). HandlerFunc(func(w http.ResponseWriter, r *http.Request) { bodyBytes, err := io.ReadAll(r.Body) if err != nil { t.Fatal(err) } - var req apitest.GraphQLRequestBody + var req spectest.GraphQLRequestBody if err := json.Unmarshal(bodyBytes, &req); err != nil { t.Fatal(err) } - assert.Equal(t, apitest.GraphQLRequestBody{ + assert.Equal(t, spectest.GraphQLRequestBody{ Query: `query { todos { text } }`, }, req) @@ -499,19 +499,19 @@ func TestApiTestGraphQLQuery(t *testing.T) { } func TestApiTestGraphQLRequest(t *testing.T) { - apitest.New(). + spectest.New(). HandlerFunc(func(w http.ResponseWriter, r *http.Request) { bodyBytes, err := io.ReadAll(r.Body) if err != nil { t.Fatal(err) } - var req apitest.GraphQLRequestBody + var req spectest.GraphQLRequestBody if err := json.Unmarshal(bodyBytes, &req); err != nil { t.Fatal(err) } - expected := apitest.GraphQLRequestBody{ + expected := spectest.GraphQLRequestBody{ Query: `query { todos { text } }`, OperationName: "myOperation", Variables: map[string]interface{}{ @@ -525,7 +525,7 @@ func TestApiTestGraphQLRequest(t *testing.T) { w.WriteHeader(http.StatusOK) }). Post("/query"). - GraphQLRequest(apitest.GraphQLRequestBody{ + GraphQLRequest(spectest.GraphQLRequestBody{ Query: "query { todos { text } }", Variables: map[string]interface{}{ "a": 1, @@ -549,7 +549,7 @@ func TestApiTestMatchesJSONResponseBody(t *testing.T) { } }) - apitest.New(). + spectest.New(). Handler(handler). Get("/hello"). Expect(t). @@ -569,7 +569,7 @@ func TestApiTestMatchesJSONResponseBodyWithFormatter(t *testing.T) { } }) - apitest.New(). + spectest.New(). Handler(handler). Get("/hello"). Expect(t). @@ -592,7 +592,7 @@ func TestApiTestMatchesJSONBodyFromFile(t *testing.T) { } }) - apitest.New(). + spectest.New(). Handler(handler). Post("/hello"). JSONFromFile("testdata/request_body.json"). @@ -616,7 +616,7 @@ func TestApiTestMatchesBodyFromFile(t *testing.T) { } }) - apitest.New(). + spectest.New(). Handler(handler). Post("/hello"). BodyFromFile("testdata/request_body.json"). @@ -638,7 +638,7 @@ func TestApiTestMatchesJSONResponseBodyWithWhitespace(t *testing.T) { } }) - apitest.New(). + spectest.New(). Handler(handler). Get("/hello"). Expect(t). @@ -661,7 +661,7 @@ func TestApiTestMatchesTextResponseBody(t *testing.T) { } }) - apitest.New(). + spectest.New(). Handler(handler). Get("/hello"). Expect(t). @@ -698,14 +698,14 @@ func TestApiTestMatchesResponseCookies(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Patch("/hello"). Expect(t). Status(http.StatusOK). Cookies( - apitest.NewCookie("ABC").Value("12345"), - apitest.NewCookie("DEF").Value("67890")). + spectest.NewCookie("ABC").Value("12345"), + spectest.NewCookie("DEF").Value("67890")). Cookie("YYY", "kfiufhtne"). CookiePresent("XXX"). CookiePresent("VVV"). @@ -728,13 +728,13 @@ func TestApiTestMatchesResponseHttpCookies(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Get("/hello"). Expect(t). Cookies( - apitest.NewCookie("ABC").Value("12345"), - apitest.NewCookie("DEF").Value("67890")). + spectest.NewCookie("ABC").Value("12345"), + spectest.NewCookie("DEF").Value("67890")). End() } @@ -757,12 +757,12 @@ func TestApiTestMatchesResponseHttpCookies_OnlySuppliedFields(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Get("/hello"). Expect(t). Cookies( - apitest.NewCookie("session_id"). + spectest.NewCookie("session_id"). Value("pdsanjdna_8e8922"). Path("/"). Expires(parsedDateTime). @@ -782,7 +782,7 @@ func TestApiTestMatchesResponseHeadersWithMixedKeyCase(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Get("/hello"). Expect(t). @@ -806,7 +806,7 @@ func TestApiTestEndReturnsTheResult(t *testing.T) { } var r resBody - apitest.New(). + spectest.New(). HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) w.Header().Set("Content-Type", "application/json") @@ -835,27 +835,27 @@ func TestApiTestCustomAssert(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Patch("/hello"). Expect(t). - Assert(apitest.IsSuccess). + Assert(spectest.IsSuccess). End() } func TestApiTestVerifierCapturesTheTestMessage(t *testing.T) { verifier := mocks.NewVerifier() - verifier.EqualFn = func(t apitest.TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + verifier.EqualFn = func(t spectest.TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if expected == http.StatusOK { return true } - args := msgAndArgs[0].(interface{}).([]interface{}) + args := msgAndArgs[0].([]interface{}) assert.Equal(t, 2, len(args)) assert.Equal(t, "expected header 'Abc' not present in response", args[0].(string)) return true } - apitest.New("the test case name"). + spectest.New("the test case name"). HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"id": "1234", "name": "Andy"}`)) w.WriteHeader(http.StatusOK) @@ -869,7 +869,7 @@ func TestApiTestVerifierCapturesTheTestMessage(t *testing.T) { } func TestApiTestReport(t *testing.T) { - getUser := apitest.NewMock(). + getUser := spectest.NewMock(). Get("http://localhost:8080"). RespondWith(). Status(http.StatusOK). @@ -879,7 +879,7 @@ func TestApiTestReport(t *testing.T) { reporter := &RecorderCaptor{} - apitest.New("some test"). + spectest.New("some test"). Debug(). Meta(map[string]interface{}{"host": "abc.com"}). Report(reporter). @@ -908,7 +908,7 @@ func TestApiTestReport(t *testing.T) { } func TestApiTestRecorder(t *testing.T) { - getUser := apitest.NewMock(). + getUser := spectest.NewMock(). Get("http://localhost:8080"). RespondWith(). Status(http.StatusOK). @@ -917,25 +917,25 @@ func TestApiTestRecorder(t *testing.T) { End() reporter := &RecorderCaptor{} - messageRequest := apitest.MessageRequest{ + messageRequest := spectest.MessageRequest{ Source: "Source", Target: "Target", Header: "Header", Body: "Body", Timestamp: time.Now().UTC(), } - messageResponse := apitest.MessageResponse{ + messageResponse := spectest.MessageResponse{ Source: "Source", Target: "Target", Header: "Header", Body: "Body", Timestamp: time.Now().UTC(), } - recorder := apitest.NewTestRecorder() + recorder := spectest.NewTestRecorder() recorder.AddMessageRequest(messageRequest) recorder.AddMessageResponse(messageResponse) - apitest.New("some test"). + spectest.New("some test"). Meta(map[string]interface{}{"host": "abc.com"}). Report(reporter). Recorder(recorder). @@ -964,8 +964,8 @@ func TestApiTestObserve(t *testing.T) { }) observeCalled := false - apitest.New("observe test"). - Observe(func(res *http.Response, req *http.Request, apiTest *apitest.APITest) { + spectest.New("observe test"). + Observe(func(res *http.Response, req *http.Request, apiTest *spectest.APITest) { observeCalled = true assert.Equal(t, http.StatusOK, res.StatusCode) assert.Equal(t, "/hello", req.URL.Path) @@ -990,7 +990,7 @@ func TestApiTestObserveDumpsTheHttpRequestAndResponse(t *testing.T) { } }) - apitest.New(). + spectest.New(). Handler(handler). Post("/hello"). Body(`{"a": 12345}`). @@ -1008,9 +1008,9 @@ func TestApiTestObserveWithReport(t *testing.T) { }) observeCalled := false - apitest.New("observe test"). + spectest.New("observe test"). Report(reporter). - Observe(func(res *http.Response, req *http.Request, apiTest *apitest.APITest) { + Observe(func(res *http.Response, req *http.Request, apiTest *spectest.APITest) { observeCalled = true assert.Equal(t, http.StatusOK, res.StatusCode) assert.Equal(t, "/hello", req.URL.Path) @@ -1039,7 +1039,7 @@ func TestApiTestIntercept(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Intercept(func(req *http.Request) { req.URL.RawQuery = "a[]=xxx&a[]=yyy" @@ -1053,7 +1053,7 @@ func TestApiTestIntercept(t *testing.T) { } func TestApiTestExposesRequestAndResponse(t *testing.T) { - apiTest := apitest.New() + apiTest := spectest.New() assert.Equal(t, true, apiTest.Request() != nil) assert.Equal(t, true, apiTest.Response() != nil) @@ -1071,7 +1071,7 @@ func TestApiTestRequestContextIsPreserved(t *testing.T) { *r = *r.WithContext(context.WithValue(r.Context(), ctxKey, []byte("world"))) } - apitest.New(). + spectest.New(). Handler(handler). Intercept(interceptor). Get("/hello"). @@ -1091,9 +1091,9 @@ func TestApiTestNoopVerifier(t *testing.T) { } }) - apitest.New(). + spectest.New(). Handler(handler). - Verifier(apitest.NoopVerifier{}). + Verifier(spectest.NoopVerifier{}). Get("/hello"). Expect(t). Body(`{"a": 123456}`). @@ -1102,7 +1102,7 @@ func TestApiTestNoopVerifier(t *testing.T) { } // TestRealNetworking creates a server with two endpoints, /login sets a token via a cookie and /authenticated_resource -// validates the token. A cookie jar is used to verify session persistence across multiple apitest instances +// validates the token. A cookie jar is used to verify session persistence across multiple spectest instances func TestRealNetworking(t *testing.T) { srv := &http.Server{Addr: "localhost:9876"} finish := make(chan struct{}) @@ -1147,14 +1147,14 @@ func TestRealNetworking(t *testing.T) { Jar: cookieJar, } - apitest.New(). + spectest.New(). EnableNetworking(cli). Get("http://localhost:9876/login"). Expect(t). Status(203). End() - apitest.New(). + spectest.New(). EnableNetworking(cli). Get("http://localhost:9876/authenticated_resource"). Expect(t). @@ -1197,7 +1197,7 @@ func TestApiTestAddsUrlEncodedFormBody(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Post("/hello"). FormData("name", "John"). @@ -1269,7 +1269,7 @@ func TestApiTestAddsMultipartFormData(t *testing.T) { w.WriteHeader(http.StatusOK) }) - apitest.New(). + spectest.New(). Handler(handler). Post("/hello"). MultipartFormData("name", "John"). @@ -1286,14 +1286,14 @@ func TestApiTestAddsMultipartFormData(t *testing.T) { func TestApiTestCombineFormDataWithMultipart(t *testing.T) { if os.Getenv("RUN_FATAL_TEST") == "FormData" { - apitest.New(). + spectest.New(). Post("/hello"). MultipartFormData("name", "John"). FormData("name", "John") return } if os.Getenv("RUN_FATAL_TEST") == "File" { - apitest.New(). + spectest.New(). Post("/hello"). MultipartFile("file", "testdata/request_body.json"). FormData("name", "John") @@ -1320,7 +1320,7 @@ func TestApiTestCombineFormDataWithMultipart(t *testing.T) { } func TestApiTestErrorIfMockInvocationsDoNotMatchTimes(t *testing.T) { - getUser := apitest.NewMock(). + getUser := spectest.NewMock(). Get("http://localhost:8080"). RespondWith(). Status(http.StatusOK). @@ -1328,12 +1328,12 @@ func TestApiTestErrorIfMockInvocationsDoNotMatchTimes(t *testing.T) { End() verifier := mocks.NewVerifier() - verifier.FailFn = func(t apitest.TestingT, failureMessage string, msgAndArgs ...interface{}) bool { + verifier.FailFn = func(t spectest.TestingT, failureMessage string, msgAndArgs ...interface{}) bool { assert.Equal(t, "mock was not invoked expected times", failureMessage) return true } - res := apitest.New(). + res := spectest.New(). Mocks(getUser). Verifier(verifier). Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -1351,14 +1351,14 @@ func TestApiTestErrorIfMockInvocationsDoNotMatchTimes(t *testing.T) { } func TestApiTestMatchesTimes(t *testing.T) { - getUser := apitest.NewMock(). + getUser := spectest.NewMock(). Get("http://localhost:8080"). RespondWith(). Status(http.StatusOK). Times(1). End() - res := apitest.New(). + res := spectest.New(). Mocks(getUser). Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _ = getUserData() @@ -1373,10 +1373,10 @@ func TestApiTestMatchesTimes(t *testing.T) { } type RecorderCaptor struct { - capturedRecorder apitest.Recorder + capturedRecorder spectest.Recorder } -func (r *RecorderCaptor) Format(recorder *apitest.Recorder) { +func (r *RecorderCaptor) Format(recorder *spectest.Recorder) { r.capturedRecorder = *recorder } @@ -1392,4 +1392,4 @@ func getUserData() []byte { return data } -var assert = apitest.DefaultVerifier{} +var assert = spectest.DefaultVerifier{} diff --git a/x/db/db.go b/x/db/db.go index b7c7a85..358f9db 100644 --- a/x/db/db.go +++ b/x/db/db.go @@ -1,3 +1,5 @@ +// Package db provides a wrapper for database/sql to record SQL queries and results. +// This package is too old. Need to update it to support the latest version of database/sql package db import ( @@ -9,11 +11,11 @@ import ( "io" "time" - apitest "github.com/go-spectest/spectest" + "github.com/go-spectest/spectest" ) // WrapWithRecorder wraps an existing driver with a Recorder -func WrapWithRecorder(driverName string, recorder *apitest.Recorder) driver.Driver { +func WrapWithRecorder(driverName string, recorder *spectest.Recorder) driver.Driver { sqlDriver := sqlDriverNameToDriver(driverName) recordingDriver := &recordingDriver{ sourceName: driverName, @@ -29,13 +31,13 @@ func WrapWithRecorder(driverName string, recorder *apitest.Recorder) driver.Driv } // WrapConnectorWithRecorder wraps an existing connector with a Recorder -func WrapConnectorWithRecorder(connector driver.Connector, sourceName string, recorder *apitest.Recorder) driver.Connector { +func WrapConnectorWithRecorder(connector driver.Connector, sourceName string, recorder *spectest.Recorder) driver.Connector { return &recordingConnector{recorder: recorder, sourceName: sourceName, Connector: connector} } type recordingDriver struct { Driver driver.Driver - recorder *apitest.Recorder + recorder *spectest.Recorder sourceName string } @@ -46,9 +48,7 @@ func (d *recordingDriver) Open(name string) (driver.Conn, error) { return nil, err } - _, isConnQuery := conn.(driver.Queryer) _, isConnQueryCtx := conn.(driver.QueryerContext) - _, isConnExec := conn.(driver.Execer) _, isConnExecCtx := conn.(driver.ExecerContext) _, isConnPrepareCtx := conn.(driver.ConnPrepareContext) recordingConn := &recordingConn{Conn: conn, recorder: d.recorder, sourceName: d.sourceName} @@ -63,15 +63,6 @@ func (d *recordingDriver) Open(name string) (driver.Conn, error) { &recordingConnWithPing{recordingConn}, }, nil } - - if isConnQuery && isConnExec { - return &recordingConnWithExecQuery{ - recordingConn, - &recordingConnWithExec{recordingConn}, - &recordingConnWithQuery{recordingConn}, - }, nil - } - return recordingConn, nil } @@ -94,7 +85,7 @@ func (d *recordingDriverContext) OpenConnector(name string) (driver.Connector, e type recordingConnector struct { Connector driver.Connector - recorder *apitest.Recorder + recorder *spectest.Recorder sourceName string } @@ -104,10 +95,7 @@ func (c *recordingConnector) Connect(context context.Context) (driver.Conn, erro if err != nil { return nil, err } - - _, isConnQuery := conn.(driver.Queryer) _, isConnQueryCtx := conn.(driver.QueryerContext) - _, isConnExec := conn.(driver.Execer) _, isConnExecCtx := conn.(driver.ExecerContext) _, isConnPrepareCtx := conn.(driver.ConnPrepareContext) recordingConn := &recordingConn{Conn: conn, recorder: c.recorder, sourceName: c.sourceName} @@ -122,15 +110,6 @@ func (c *recordingConnector) Connect(context context.Context) (driver.Conn, erro &recordingConnWithPing{recordingConn}, }, nil } - - if isConnQuery && isConnExec { - return &recordingConnWithExecQuery{ - recordingConn, - &recordingConnWithExec{recordingConn}, - &recordingConnWithQuery{recordingConn}, - }, nil - } - return recordingConn, nil } @@ -139,7 +118,7 @@ func (c *recordingConnector) Driver() driver.Driver { return c.Connector.Driver( type recordingConn struct { Conn driver.Conn - recorder *apitest.Recorder + recorder *spectest.Recorder sourceName string } @@ -194,8 +173,8 @@ func (conn *recordingConnWithQuery) Query(query string, args []driver.Value) (dr if len(args) > 0 { recorderBody = fmt.Sprintf("%s %+v", query, args) } - conn.recorder.AddMessageRequest(apitest.MessageRequest{ - Source: apitest.SystemUnderTestDefaultName, + conn.recorder.AddMessageRequest(spectest.MessageRequest{ + Source: spectest.SystemUnderTestDefaultName, Target: conn.sourceName, Header: "SQL Query", Body: recorderBody, @@ -206,7 +185,7 @@ func (conn *recordingConnWithQuery) Query(query string, args []driver.Value) (dr return &recordingRows{Rows: rows, recorder: conn.recorder, sourceName: conn.sourceName}, err } - return nil, errors.New("Queryer not implemented") + return nil, errors.New("queryer not implemented") } type recordingConnWithQueryContext struct { @@ -231,8 +210,8 @@ func (conn *recordingConnWithQueryContext) QueryContext(ctx context.Context, que } recorderBody = fmt.Sprintf("%s %+v", query, convertedArgs) } - conn.recorder.AddMessageRequest(apitest.MessageRequest{ - Source: apitest.SystemUnderTestDefaultName, + conn.recorder.AddMessageRequest(spectest.MessageRequest{ + Source: spectest.SystemUnderTestDefaultName, Target: conn.sourceName, Header: "SQL Query", Body: recorderBody, @@ -264,8 +243,8 @@ func (conn *recordingConnWithExec) Exec(query string, args []driver.Value) (driv if len(args) > 0 { recorderBody = fmt.Sprintf("%s %+v", query, args) } - conn.recorder.AddMessageRequest(apitest.MessageRequest{ - Source: apitest.SystemUnderTestDefaultName, + conn.recorder.AddMessageRequest(spectest.MessageRequest{ + Source: spectest.SystemUnderTestDefaultName, Target: conn.sourceName, Header: "SQL Query", Body: recorderBody, @@ -275,9 +254,9 @@ func (conn *recordingConnWithExec) Exec(query string, args []driver.Value) (driv if result != nil && conn.recorder != nil { rowsAffected, _ := result.RowsAffected() - conn.recorder.AddMessageResponse(apitest.MessageResponse{ + conn.recorder.AddMessageResponse(spectest.MessageResponse{ Source: conn.sourceName, - Target: apitest.SystemUnderTestDefaultName, + Target: spectest.SystemUnderTestDefaultName, Header: "SQL Result", Body: fmt.Sprintf("Affected rows: %d", rowsAffected), Timestamp: time.Now().UTC(), @@ -287,7 +266,7 @@ func (conn *recordingConnWithExec) Exec(query string, args []driver.Value) (driv return result, err } - return nil, errors.New("Execer not implemented") + return nil, errors.New("execer not implemented") } type recordingConnWithExecContext struct { @@ -312,8 +291,8 @@ func (conn *recordingConnWithExecContext) ExecContext(ctx context.Context, query } recorderBody = fmt.Sprintf("%s %+v", query, convertedArgs) } - conn.recorder.AddMessageRequest(apitest.MessageRequest{ - Source: apitest.SystemUnderTestDefaultName, + conn.recorder.AddMessageRequest(spectest.MessageRequest{ + Source: spectest.SystemUnderTestDefaultName, Target: conn.sourceName, Header: "SQL Query", Body: recorderBody, @@ -323,9 +302,9 @@ func (conn *recordingConnWithExecContext) ExecContext(ctx context.Context, query if result != nil && conn.recorder != nil { rowsAffected, _ := result.RowsAffected() - conn.recorder.AddMessageResponse(apitest.MessageResponse{ + conn.recorder.AddMessageResponse(spectest.MessageResponse{ Source: conn.sourceName, - Target: apitest.SystemUnderTestDefaultName, + Target: spectest.SystemUnderTestDefaultName, Header: "SQL Result", Body: fmt.Sprintf("Affected rows: %d", rowsAffected), Timestamp: time.Now().UTC(), @@ -420,7 +399,7 @@ type recordingConnWithExecQueryPrepareContext struct { type recordingStmt struct { Stmt driver.Stmt - recorder *apitest.Recorder + recorder *spectest.Recorder sourceName string query string } @@ -444,8 +423,8 @@ func (stmt *recordingStmt) Exec(args []driver.Value) (driver.Result, error) { if len(args) > 0 { recorderBody = fmt.Sprintf("%s %+v", stmt.query, args) } - stmt.recorder.AddMessageRequest(apitest.MessageRequest{ - Source: apitest.SystemUnderTestDefaultName, + stmt.recorder.AddMessageRequest(spectest.MessageRequest{ + Source: spectest.SystemUnderTestDefaultName, Target: stmt.sourceName, Header: "SQL Query", Body: recorderBody, @@ -455,9 +434,9 @@ func (stmt *recordingStmt) Exec(args []driver.Value) (driver.Result, error) { if result != nil && stmt.recorder != nil { rowsAffected, _ := result.RowsAffected() - stmt.recorder.AddMessageResponse(apitest.MessageResponse{ + stmt.recorder.AddMessageResponse(spectest.MessageResponse{ Source: stmt.sourceName, - Target: apitest.SystemUnderTestDefaultName, + Target: spectest.SystemUnderTestDefaultName, Header: "SQL Result", Body: fmt.Sprintf("Affected rows: %d", rowsAffected), Timestamp: time.Now().UTC(), @@ -477,8 +456,8 @@ func (stmt *recordingStmt) Query(args []driver.Value) (driver.Rows, error) { if len(args) > 0 { recorderBody = fmt.Sprintf("%s %+v", stmt.query, args) } - stmt.recorder.AddMessageRequest(apitest.MessageRequest{ - Source: apitest.SystemUnderTestDefaultName, + stmt.recorder.AddMessageRequest(spectest.MessageRequest{ + Source: spectest.SystemUnderTestDefaultName, Target: stmt.sourceName, Header: "SQL Query", Body: recorderBody, @@ -512,8 +491,8 @@ func (stmt *recordingStmtWithExecContext) ExecContext(ctx context.Context, args recorderBody = fmt.Sprintf("%s %+v", stmt.query, convertedArgs) } - stmt.recorder.AddMessageRequest(apitest.MessageRequest{ - Source: apitest.SystemUnderTestDefaultName, + stmt.recorder.AddMessageRequest(spectest.MessageRequest{ + Source: spectest.SystemUnderTestDefaultName, Target: stmt.sourceName, Header: "SQL Query", Body: recorderBody, @@ -523,9 +502,9 @@ func (stmt *recordingStmtWithExecContext) ExecContext(ctx context.Context, args if result != nil && stmt.recorder != nil { rowsAffected, _ := result.RowsAffected() - stmt.recorder.AddMessageResponse(apitest.MessageResponse{ + stmt.recorder.AddMessageResponse(spectest.MessageResponse{ Source: stmt.sourceName, - Target: apitest.SystemUnderTestDefaultName, + Target: spectest.SystemUnderTestDefaultName, Header: "SQL Result", Body: fmt.Sprintf("Affected rows: %d", rowsAffected), Timestamp: time.Now().UTC(), @@ -561,8 +540,8 @@ func (stmt *recordingStmtWithQueryContext) QueryContext(ctx context.Context, arg recorderBody = fmt.Sprintf("%s %+v", stmt.query, convertedArgs) } - stmt.recorder.AddMessageRequest(apitest.MessageRequest{ - Source: apitest.SystemUnderTestDefaultName, + stmt.recorder.AddMessageRequest(spectest.MessageRequest{ + Source: spectest.SystemUnderTestDefaultName, Target: stmt.sourceName, Header: "SQL Query", Body: recorderBody, @@ -584,7 +563,7 @@ type recordingStmtWithExecQueryContext struct { type recordingRows struct { Rows driver.Rows - recorder *apitest.Recorder + recorder *spectest.Recorder sourceName string RowsFound int } @@ -596,9 +575,9 @@ func (rows *recordingRows) Columns() []string { return rows.Rows.Columns() } // It also sends the number of rows found by the query as a message to the recorder func (rows *recordingRows) Close() error { if rows.recorder != nil { - rows.recorder.AddMessageResponse(apitest.MessageResponse{ + rows.recorder.AddMessageResponse(spectest.MessageResponse{ Source: rows.sourceName, - Target: apitest.SystemUnderTestDefaultName, + Target: spectest.SystemUnderTestDefaultName, Header: "SQL Result", Body: fmt.Sprintf("Rows returned: %d", rows.RowsFound), Timestamp: time.Now().UTC(), @@ -637,6 +616,5 @@ func sqlDriverNameToDriver(driverName string) driver.Driver { db.Close() return db.Driver() } - return nil } From 3c44c38f2690116a8db9558474807475caca991f Mon Sep 17 00:00:00 2001 From: CHIKAMATSU Naohiro Date: Thu, 5 Oct 2023 14:50:50 +0900 Subject: [PATCH 2/2] Delete unused parameter --- .octocov.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.octocov.yml b/.octocov.yml index 37421fa..43c35ab 100644 --- a/.octocov.yml +++ b/.octocov.yml @@ -5,8 +5,6 @@ coverage: badge: path: docs/coverage.svg testExecutionTime: - if: true - acceptable: 1:1.1 badge: path: docs/time.svg diff: