go-by-test/blogposts/blogposts_test.go

76 lines
1.3 KiB
Go
Raw Normal View History

2024-09-23 21:09:10 +00:00
package blogposts
import (
2024-09-24 18:57:28 +00:00
"reflect"
2024-09-23 21:09:10 +00:00
"testing"
"testing/fstest"
)
// NOTE: This should be a black box test outside blogposts package.
2024-09-24 18:57:28 +00:00
// NOTE: If we want to test the return error
//
// type StubFailingFS struct{}
//
// func (s StubFailingFS) Open(name string) (fs.File, error) {
// return nil, errors.New("fail")
// }
2024-09-23 21:09:10 +00:00
func TestNewBlogPosts(t *testing.T) {
2024-09-24 19:26:42 +00:00
const (
firstBody = `Title: Post 1
2024-09-24 19:38:21 +00:00
Description: Description 1
2024-09-24 19:51:09 +00:00
Tags: tdd, go
---
Hello
World`
2024-09-24 19:26:42 +00:00
secondBody = `Title: Post 2
2024-09-24 19:38:21 +00:00
Description: Description 2
2024-09-24 19:51:09 +00:00
Tags: rust, borrow-checker
---
B
L
M`
2024-09-24 19:26:42 +00:00
)
2024-09-23 21:09:10 +00:00
fs := fstest.MapFS{
2024-09-24 19:26:42 +00:00
"hello world.md": {Data: []byte(firstBody)},
"hello-world2.md": {Data: []byte(secondBody)},
2024-09-24 18:57:28 +00:00
}
posts, err := NewPostsFromFS(fs)
if err != nil {
t.Fatal(err)
2024-09-23 21:09:10 +00:00
}
if len(posts) != len(fs) {
t.Errorf("got %d posts, wanted %d posts", len(posts), len(fs))
}
2024-09-24 18:57:28 +00:00
2024-09-24 19:26:42 +00:00
assertPost(t, posts[0], Post{
Title: "Post 1",
Description: "Description 1",
2024-09-24 19:51:09 +00:00
Tags: []string{"tdd", "go"},
Body: `Hello
World`,
2024-09-24 19:26:42 +00:00
})
}
2024-09-24 18:57:28 +00:00
2024-09-24 20:13:33 +00:00
func TestWrongFile(t *testing.T) {
fs := fstest.MapFS{
"hello world.txt": {Data: []byte("Yolo")},
}
_, err := NewPostsFromFS(fs)
if err == nil {
t.Errorf("should be an error but not")
}
}
func assertPost(t testing.TB, got Post, want Post) {
t.Helper()
2024-09-24 18:57:28 +00:00
if !reflect.DeepEqual(got, want) {
t.Errorf("got %+v, want %+v", got, want)
}
2024-09-23 21:09:10 +00:00
}