posts_test.gno

2.52 Kb ยท 103 lines
  1package minisocial
  2
  3import (
  4	"std"
  5	"strings"
  6	"testing"
  7
  8	"gno.land/p/demo/testutils" // Provides testing utilities
  9)
 10
 11func TestCreatePostSingle(t *testing.T) {
 12	// Get a test address for alice
 13	aliceAddr := testutils.TestAddress("alice")
 14	// TestSetRealm sets the realm caller, in this case Alice
 15	testing.SetRealm(std.NewUserRealm(aliceAddr))
 16
 17	text1 := "Hello World!"
 18	err := CreatePost(text1)
 19	if err != nil {
 20		t.Fatalf("expected no error, got %v", err)
 21	}
 22
 23	// Get the rendered page
 24	got := Render("")
 25
 26	// Content should have the text and alice's address in it
 27	if !(strings.Contains(got, text1) && strings.Contains(got, aliceAddr.String())) {
 28		t.Fatal("expected render to contain text & alice's address")
 29	}
 30}
 31
 32func TestCreatePostMultiple(t *testing.T) {
 33	// Initialize a slice to hold the test posts and their authors
 34	posts := []struct {
 35		text   string
 36		author string
 37	}{
 38		{"Hello World!", "alice"},
 39		{"This is some new text!", "bob"},
 40		{"Another post by alice", "alice"},
 41		{"A post by charlie!", "charlie"},
 42	}
 43
 44	for _, p := range posts {
 45		// Set the appropriate caller realm based on the author
 46		authorAddr := testutils.TestAddress(p.author)
 47		testing.SetRealm(std.NewUserRealm(authorAddr))
 48
 49		// Create the post
 50		err := CreatePost(p.text)
 51		if err != nil {
 52			t.Fatalf("expected no error for post '%s', got %v", p.text, err)
 53		}
 54	}
 55
 56	// Get the rendered page
 57	got := Render("")
 58
 59	// Check that all posts and their authors are present in the rendered output
 60	for _, p := range posts {
 61		expectedText := p.text
 62		expectedAuthor := testutils.TestAddress(p.author).String() // Get the address for the author
 63		if !(strings.Contains(got, expectedText) && strings.Contains(got, expectedAuthor)) {
 64			t.Fatalf("expected render to contain text '%s' and address '%s'", expectedText, expectedAuthor)
 65		}
 66	}
 67}
 68
 69func TestReset(t *testing.T) {
 70	aliceAddr := testutils.TestAddress("alice")
 71	testing.SetRealm(std.NewUserRealm(aliceAddr))
 72
 73	text1 := "Hello World!"
 74	_ = CreatePost(text1)
 75
 76	got := Render("")
 77	if !strings.Contains(got, text1) {
 78		t.Fatal("expected render to contain text1")
 79	}
 80
 81	// Set admin
 82	testing.SetRealm(std.NewUserRealm(Ownable.Owner()))
 83	ResetPosts()
 84
 85	got = Render("")
 86	if strings.Contains(got, text1) {
 87		t.Fatal("expected render to not contain text1")
 88	}
 89
 90	text2 := "Some other Text!!"
 91	_ = CreatePost(text2)
 92
 93	got = Render("")
 94	if strings.Contains(got, text1) {
 95		t.Fatal("expected render to not contain text1")
 96	}
 97
 98	if !strings.Contains(got, text2) {
 99		t.Fatal("expected render to contain text2")
100	}
101}
102
103// TODO: Add tests for Update & Delete