diff options
| author | Shulhan <ms@kilabit.info> | 2024-12-11 02:32:06 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2024-12-28 14:37:31 +0700 |
| commit | bb39eaaed31306a7d29cee4cee75092c0d6a2191 (patch) | |
| tree | 079997bdf4cfa74c98c8a94f8a2818c8fb7f267a /lib/play/http_example_test.go | |
| parent | 632c367b5ad48df8d223bab64daf2e23ceaccabb (diff) | |
| download | pakakeh.go-bb39eaaed31306a7d29cee4cee75092c0d6a2191.tar.xz | |
lib/play: implement function to test Go code
The Test and HTTPHandleTest functions accept Request with File and Body
fields.
Diffstat (limited to 'lib/play/http_example_test.go')
| -rw-r--r-- | lib/play/http_example_test.go | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/lib/play/http_example_test.go b/lib/play/http_example_test.go new file mode 100644 index 00000000..6752e175 --- /dev/null +++ b/lib/play/http_example_test.go @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: 2024 M. Shulhan <ms@kilabit.info> +// +// SPDX-License-Identifier: BSD-3-Clause + +package play + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "net/http/httptest" + "regexp" +) + +func ExampleHTTPHandleTest() { + const code = ` +package test +import "testing" +func TestSum(t *testing.T) { + var total = sum(1, 2, 3) + if total != 6 { + t.Fatalf("got %d, want 6", total) + } +}` + var req = Request{ + Body: code, + File: `testdata/test_test.go`, + } + var ( + rawbody []byte + err error + ) + rawbody, err = json.Marshal(&req) + if err != nil { + log.Fatal(err) + } + + var mux = http.NewServeMux() + + mux.HandleFunc(`POST /api/play/test`, HTTPHandleTest) + + var resprec = httptest.NewRecorder() + var httpreq = httptest.NewRequest(`POST`, `/api/play/test`, + bytes.NewReader(rawbody)) + httpreq.Header.Set(`Content-Type`, `application/json`) + + mux.ServeHTTP(resprec, httpreq) + var resp = resprec.Result() + + rawbody, err = io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + + var rexDuration = regexp.MustCompile(`(?m)\\t(\d+\.\d+)s`) + rawbody = rexDuration.ReplaceAll(rawbody, []byte(`\tXs`)) + + fmt.Printf(`%s`, rawbody) + + // Output: + // {"data":"ok \tgit.sr.ht/~shulhan/pakakeh.go/lib/play/testdata\tXs\n","code":200} +} |
