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
import "io/fs"
import (
"io"
"io/fs"
)
type Post struct {
Title, Description, Body string
Tags []string
}
func NewPostsFromFS(fs fs.FS) []Post {
return []Post{{}, {}}
func NewPostsFromFS(fileSystem fs.FS) ([]Post, error) {
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
import (
"reflect"
"testing"
"testing/fstest"
)
// 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) {
fs := fstest.MapFS{
"hello world.md": {Data: []byte("hi")},
"hello-world2.md": {Data: []byte("hola")},
"hello world.md": {Data: []byte("Title: Post 1")},
"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) {
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)
}
}