Powerful Command-Line Applications in Go: TestParseContent & TestRun failed (pages 53 - 54)

Tests on compare 2 slice of byte fail because there is a difference in the formatting we get after the parseContent()
and goldenFile
functions. The difference lies in different tabulation.
To bring them to a common state I suggest using the package go get -u github.com/yosssi/gohtml
func formatHTML(data []byte) []byte {
// Convert to string for manipulation
content := string(data)
formattedHTML := gohtml.Format(content)
// Return the formatted html as []byte
return []byte(formattedHTML)
}
This formatHTML function will take raw HTML in a []byte
format, format it using gohtml, and return the formatted HTML as []byte
. Here’s a quick breakdown of how it works:
Conversion to String: string(data)
converts the byte slice to a string, as gohtml.Format requires a string input.
Formatting*: gohtml.Format(content)
processes the HTML string, adding indentation and spacing for readability.
Returning as []byte
: []byte(formattedHTML)
converts the formatted string back to []byte
.
if !bytes.Equal(formatHTML(expected), formatHTML(result)) {
t.Logf("golden:\n%s\n", formatHTML(expected))
t.Logf("result:\n%s\n", formatHTML(result))
t.Error("Result content doesn't match golden file")
}
Popular Prag Prog topics










Other popular topics










Latest in PragProg
Latest (all)
Categories:
Popular Portals
- /elixir
- /opensuse
- /rust
- /kotlin
- /ruby
- /erlang
- /python
- /clojure
- /react
- /quarkus
- /go
- /vapor
- /v
- /react-native
- /wasm
- /security
- /django
- /nodejs
- /centos
- /haskell
- /rails
- /fable
- /gleam
- /swift
- /js
- /deno
- /assemblyscript
- /tailwind
- /laravel
- /symfony
- /phoenix
- /crystal
- /typescript
- /debian
- /adonisjs
- /julia
- /arch-linux
- /svelte
- /spring
- /flutter
- /c-plus-plus
- /preact
- /actix
- /java
- /angular
- /ocaml
- /zig
- /kubuntu
- /scala
- /zotonic
- /vim
- /rocky
- /lisp
- /html
- /keyboards
- /nim
- /vuejs
- /emacs
- /elm
- /nerves