Skip to content

Commit

Permalink
test: use wasmbrowsertest to report coverage
Browse files Browse the repository at this point in the history
Signed-off-by: Zxilly <[email protected]>
  • Loading branch information
Zxilly committed Jun 17, 2024
1 parent a6ace68 commit d0ea96f
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 23 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ jobs:
- name: Setup Go global dependencies
run: |
go install github.com/jstemmer/go-junit-report/v2@85bf4716ac1f025f2925510a9f5e9f5bb347c009
go install github.com/Zxilly/go_js_wasm_exec@17f8c465d89b47d00637caf8ca7b38d20de31f5b
go install github.com/agnivade/wasmbrowsertest@4a40c545817dd154cb5474d57c086d2371355b5a
- uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0
with:
Expand Down
1 change: 1 addition & 0 deletions .goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ builds:
- "-pgo=default.pgo"
tags:
- embed
- nethttpomithttp2

archives:
- format: tar.gz
Expand Down
3 changes: 2 additions & 1 deletion internal/entity/package_js_wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ func (p *Package) MarshalJavaScript() any {
var symbols, files []any
symbols = lo.Map(p.Symbols, func(s *Symbol, _ int) any { return s.MarshalJavaScript() })
files = lo.Map(p.Files, func(f *File, _ int) any { return f.MarshalJavaScript() })
subs := p.SubPackages.MarshalJavaScript()

return map[string]any{
"name": p.Name,
"type": p.Type,
"size": p.Size,
"symbols": symbols,
"subPackages": p.SubPackages.MarshalJavaScript(),
"subPackages": subs,
"files": files,
}
}
16 changes: 6 additions & 10 deletions internal/result/result_js_wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,18 @@

package result

import (
"github.com/samber/lo"

"github.com/Zxilly/go-size-analyzer/internal/entity"
)

func (r *Result) MarshalJavaScript() any {
var sections []any
sections = lo.Map(r.Sections, func(s *entity.Section, _ int) any {
return s.MarshalJavaScript()
})
for _, s := range r.Sections {
sections = append(sections, s.MarshalJavaScript())
}

packages := r.Packages.MarshalJavaScript()

return map[string]any{
"name": r.Name,
"size": r.Size,
"packages": r.Packages.MarshalJavaScript(),
"packages": packages,
"sections": sections,
}
}
35 changes: 29 additions & 6 deletions internal/result/result_js_wasm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import (
"compress/gzip"
_ "embed"
"encoding/gob"

"syscall/js"
"testing"

"github.com/go-json-experiment/json"

"github.com/Zxilly/go-size-analyzer/internal/result"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand All @@ -26,15 +27,37 @@ func TestResultMarshalJavaScript(t *testing.T) {
decompressedReader, err := gzip.NewReader(bytes.NewReader(testdataGob))
require.NoError(t, err)

// use JSON.stringify to compare the result
JSON := js.Global().Get("JSON")
stringify := JSON.Get("stringify")

var r result.Result
err = gob.NewDecoder(decompressedReader).Decode(&r)
require.NoError(t, err)

jsValue := r.MarshalJavaScript()
t.Run("Result", func(t *testing.T) {
jsVal := r.MarshalJavaScript()
jsStr := stringify.Invoke(jsVal).String()
assert.JSONEq(t, testdataJSON, jsStr)
})

// use JSON.stringify to compare the result
JSON := js.Global().Get("JSON")
jsonValue := JSON.Call("stringify", jsValue).String()
var testdataJSONVal map[string]any
err = json.Unmarshal([]byte(testdataJSON), &testdataJSONVal)
require.NoError(t, err)

t.Run("Section", func(t *testing.T) {
sectionsAny := testdataJSONVal["sections"].([]any)

for i, sect := range r.Sections {
jsVal := sect.MarshalJavaScript()
jsStr := stringify.Invoke(jsVal).String()

sectAny := sectionsAny[i]
sectStr, err := json.Marshal(sectAny)
require.NoError(t, err)

assert.JSONEq(t, string(sectStr), jsStr)
}
})

assert.JSONEq(t, testdataJSON, jsonValue)
}
46 changes: 41 additions & 5 deletions scripts/tests.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import os.path
import shutil
import subprocess
import time
from argparse import ArgumentParser

import requests
import subprocess
import time

from tool.gsa import build_gsa
from tool.junit import generate_junit
Expand All @@ -29,7 +30,7 @@ def run_unit_tests():
"go",
"test",
"-v",
"-covermode=atomic",
"-covermode=count",
"-cover",
"-tags=embed",
"./...",
Expand Down Expand Up @@ -59,7 +60,7 @@ def run_unit_tests():
"go",
"test",
"-v",
"-covermode=atomic",
"-covermode=count",
"-cover",
"./internal/webui",
f"-test.gocoverdir={unit_path}"
Expand All @@ -83,7 +84,40 @@ def run_unit_tests():

try:
log("Running WebAssembly unit tests...")

# download wasm_exec.js to workaround go toolchain
log("Ensuring wasm_exec.js...")
goroot = subprocess.run(["go", "env", "GOROOT"], text=True, stdout=subprocess.PIPE).stdout.strip()
wasm_exec_path = os.path.join(goroot, "misc", "wasm", "wasm_exec.js")

# mkdir
ensure_dir(os.path.dirname(wasm_exec_path))

if os.path.exists(wasm_exec_path):
log("wasm_exec.js already exists.")
else:
content = requests.get("https://raw.githubusercontent.com/golang/go/master/misc/wasm/wasm_exec.js").text
with open(wasm_exec_path, "w", encoding="utf-8") as f:
f.write(content)
log("Downloaded wasm_exec.js.")

env = os.environ.copy()
for k in list(env.keys()):
if (k.startswith("GITHUB_")
or k.startswith("JAVA_")
or k.startswith("PSMODULEPATH")
or k.startswith("PYTHONPATH")
or k.startswith("STATS_")
or k.startswith("RUNNER_")
or k.startswith("LIBRARY_")
or k == "_OLD_VIRTUAL_PATH"
):
del env[k]

wasmbrowsertest = shutil.which("wasmbrowsertest")
if wasmbrowsertest is None:
raise Exception("wasmbrowsertest is not installed. Please install wasmbrowsertest and try again.")

env["GOOS"] = "js"
env["GOARCH"] = "wasm"

Expand All @@ -92,7 +126,9 @@ def run_unit_tests():
"go",
"test",
"-v",
"-covermode=atomic",
"-gcflags=all=-N -l",
"-covermode=count",
"-exec", "wasmbrowsertest",
"-cover",
"./internal/result",
f"-test.gocoverdir={unit_path}"
Expand Down

0 comments on commit d0ea96f

Please sign in to comment.