blogposts: test get blog content

This commit is contained in:
vinchent 2024-09-24 20:57:28 +02:00
parent 048e6cccac
commit 6292463e90
2 changed files with 57 additions and 6 deletions

View File

@ -1,12 +1,43 @@
package blogposts package blogposts
import "io/fs" import (
"io"
"io/fs"
)
type Post struct { type Post struct {
Title, Description, Body string Title, Description, Body string
Tags []string Tags []string
} }
func NewPostsFromFS(fs fs.FS) []Post { func NewPostsFromFS(fileSystem fs.FS) ([]Post, error) {
return []Post{{}, {}} dir, err := fs.ReadDir(fileSystem, ".")
if err != nil {
return nil, err
}
var posts []Post
for _, f := range dir {
post, err := getPost(fileSystem, f)
if err != nil {
return nil, err
}
posts = append(posts, post)
}
return posts, nil
}
func getPost(fileSystem fs.FS, f fs.DirEntry) (Post, error) {
postFile, err := fileSystem.Open(f.Name())
if err != nil {
return Post{}, err
}
defer postFile.Close()
postData, err := io.ReadAll(postFile)
if err != nil {
return Post{}, err
}
post := Post{Title: string(postData)[7:]}
return post, nil
} }

View File

@ -1,20 +1,40 @@
package blogposts package blogposts
import ( import (
"reflect"
"testing" "testing"
"testing/fstest" "testing/fstest"
) )
// NOTE: This should be a black box test outside blogposts package. // NOTE: This should be a black box test outside blogposts package.
// 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")
// }
func TestNewBlogPosts(t *testing.T) { func TestNewBlogPosts(t *testing.T) {
fs := fstest.MapFS{ fs := fstest.MapFS{
"hello world.md": {Data: []byte("hi")}, "hello world.md": {Data: []byte("Title: Post 1")},
"hello-world2.md": {Data: []byte("hola")}, "hello-world2.md": {Data: []byte("Title: Post 2")},
}
posts, err := NewPostsFromFS(fs)
if err != nil {
t.Fatal(err)
} }
posts := NewPostsFromFS(fs)
if len(posts) != len(fs) { if len(posts) != len(fs) {
t.Errorf("got %d posts, wanted %d posts", len(posts), len(fs)) t.Errorf("got %d posts, wanted %d posts", len(posts), len(fs))
} }
got := posts[0]
want := Post{Title: "Post 1"}
if !reflect.DeepEqual(got, want) {
t.Errorf("got %+v, want %+v", got, want)
}
} }