Playground
bounded_test.gno
package threads
import (
"strconv"
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
)
// Finding 325-cost-at-caps-1 (review run 001-cd0b6a9).
//
// A Render is paid for by every reader, so its cost must be bounded by what it
// SHOWS, not by what anybody has ever written. Post and Reply are both
// permissionless and the page key is any string, so an attacker fills a page
// they do not own and every render of it inherits the cost. There is no delete
// path anywhere in threads, so it is irreversible.
//
// These tests are the invariant, not the implementation: the rendered output
// must stop growing once the collection is past the cap.
// fill posts n threads on page from n distinct addresses.
func fill(cur realm, t *testing.T, page string, n int) {
t.Helper()
for i := 0; i < n; i++ {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("filler" + strconv.Itoa(i))))
Post(cross(cur), page, "thread number "+strconv.Itoa(i))
}
}
func TestAPageRenderIsBoundedByWhatItShows(cur realm, t *testing.T) {
reset(cur)
const page = "gno.land/r/moul/home"
fill(cur, t, page, 40)
small := Render("page/" + page)
fill(cur, t, page, 160) // 200 total
big := Render("page/" + page)
rowsSmall := strings.Count(small, "\n|")
rowsBig := strings.Count(big, "\n|")
if rowsBig > rowsSmall {
t.Errorf("the page render grew from %d rows to %d when the board went from 40 threads to 200: "+
"its cost is bounded by what has been written, not by what it shows", rowsSmall, rowsBig)
}
if rowsSmall == 0 {
t.Fatal("no table rows rendered at all, so this test is measuring nothing")
}
}
func TestAThreadRenderIsBoundedByWhatItShows(cur realm, t *testing.T) {
reset(cur)
const page = "gno.land/r/moul/home"
testing.SetRealm(testing.NewUserRealm(alice))
id := Post(cross(cur), page, "a thread with many replies")
for i := 0; i < 40; i++ {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("rep" + strconv.Itoa(i))))
Reply(cross(cur), id, "reply "+strconv.Itoa(i))
}
small := Render("thread/" + strconv.FormatInt(id, 10))
for i := 40; i < 200; i++ {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("rep" + strconv.Itoa(i))))
Reply(cross(cur), id, "reply "+strconv.Itoa(i))
}
big := Render("thread/" + strconv.FormatInt(id, 10))
rowsSmall := strings.Count(small, "\n|")
rowsBig := strings.Count(big, "\n|")
if rowsBig > rowsSmall {
t.Errorf("the thread render grew from %d rows to %d when the replies went from 40 to 200: "+
"every reader pays for every reply anybody ever wrote", rowsSmall, rowsBig)
}
if rowsSmall == 0 {
t.Fatal("no table rows rendered at all, so this test is measuring nothing")
}
}
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/threads/v0" gno = "0.9" [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914348 max_deposit = "13000000ugnot"
render.gno
package threads
import (
"strconv"
"strings"
"chain/runtime"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/store/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/realmpath/v0"
th "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/threads/v0"
)
// Render routes three views: the realm's own index, one page's threads, and
// one thread.
//
// A page key contains slashes, so "page/<key>" is split on the prefix rather
// than by path element: realmpath gives the parts, and rejoining them would
// only be a way to get it wrong.
// perPage bounds every list this realm renders. A Render is paid for by every
// reader, so its cost has to be bounded by what it SHOWS rather than by what
// anybody has ever written, and both Post and Reply are permissionless with no
// delete path. 20 matches what the index already shows with board.Recent(20).
const perPage = 20
func Render(path string) string {
req := realmpath.Parse(path)
switch {
case strings.HasPrefix(req.Path, "page/"):
return renderPage(strings.TrimPrefix(req.Path, "page/"))
case strings.HasPrefix(req.Path, "thread/"):
return renderThread(strings.TrimPrefix(req.Path, "thread/"))
case req.Path == "":
return renderIndex()
default:
return md.H1("Not found") + "No such view: " + ui.Inline(req.Path)
}
}
func renderIndex() string {
out := md.H1("Threads")
out += "A discussion block any realm can embed, keyed on the page it appears on.\n\n"
t := ui.NewTable("threads", "pages", "THREAD supply")
t.Row(strconv.Itoa(board.Len()), strconv.Itoa(board.Pages()), strconv.FormatInt(points.Supply(), 10))
out += t.String()
out += md.H2("Recent, across every page")
out += listing(board.Recent(20), true)
out += md.H2("The token")
out += points.Render()
out += md.H2("Embedding it")
out += "Two lines in the host realm, and it stores nothing:\n\n"
out += md.LanguageCodeBlock("go", `import "`+realmPath+`"
func Render(path string) string {
return body + threads.RenderBlock()
}`)
out += "The page key is the host realm's own path, read off the call. " +
md.InlineCode("RenderBlockFor(page)") + " names one explicitly.\n"
return out
}
func renderPage(page string) string {
if !th.ValidPage(page) {
return md.H1("Threads") + "Not a page key: " + ui.Inline(page)
}
out := md.H1("Threads on " + ui.Inline(page))
out += md.Link("the page itself", th.RealmURL(page)) + "\n\n"
// Finding 325-cost-at-caps-1: this passed limit 0, which means "every
// thread anybody ever posted on this page". Post is permissionless and
// the page key is any string, so a visitor fills a page they do not own
// and every reader of it pays. There is no delete path, so it is
// irreversible.
total := board.PageLen(page)
out += listing(board.List(page, runtime.ChainHeight(), perPage), false)
if total > perPage {
out += md.Italic("Showing " + strconv.Itoa(perPage) + " of " +
strconv.Itoa(total) + " threads, newest and pinned first.") + "\n"
}
out += "\n" + ui.Action("π¬ Post here", "Post", "page", page, "body", "") + "\n"
return out
}
func renderThread(raw string) string {
id, ok := store.ParseID(raw)
if !ok {
return md.H1("Threads") + "Not a thread id: " + ui.Inline(raw)
}
t, found := board.Get(id)
if !found {
return md.H1("Threads") + "No thread #" + id.String()
}
out := md.H1("Thread #" + id.String())
out += md.Blockquote(ui.Inline(t.Body)) + "\n"
out += md.Italic("by "+ui.Addr(t.Author)+" Β· on "+
md.Link(t.Page, th.PageURL(realmPath, t.Page))+
" Β· "+strconv.Itoa(t.Repliers())+" earned") + "\n\n"
if t.PinnedUntil > runtime.ChainHeight() {
out += "π pinned until block " + strconv.FormatInt(t.PinnedUntil, 10) + "\n\n"
}
out += md.H2("Replies")
if len(t.Replies) == 0 {
out += ui.Empty("Nobody has replied yet.")
} else {
// Finding 325-cost-at-caps-1: this rendered every reply ever
// written. Reply is permissionless and nothing deletes one, so the
// page a reader pays for grows without a bound anybody controls.
// The newest are shown, because that is what a reader of a thread
// came for.
shown := t.Replies
if len(shown) > perPage {
shown = shown[len(shown)-perPage:]
}
r := ui.NewTable("by", "said", "block")
for _, rep := range shown {
r.Row(ui.Addr(rep.Author), ui.Cell(rep.Body), strconv.FormatInt(rep.At, 10))
}
out += r.String()
if len(t.Replies) > perPage {
out += md.Italic("Showing the newest " + strconv.Itoa(perPage) + " of " +
strconv.Itoa(len(t.Replies)) + " replies.") + "\n"
}
}
out += "\n" + ui.Action("π¬ Reply", "Reply", "threadID", id.String(), "body", "") +
" Β· " + ui.Action("π Boost", "Boost", "threadID", id.String()) + "\n"
return out
}
// listing renders a set of threads. withPage adds the page column, which the
// index needs and a page view would only repeat.
func listing(items []th.Listing, withPage bool) string {
if len(items) == 0 {
return ui.Empty("No threads yet.")
}
headers := []string{"", "#", "thread", "by", "replies"}
if withPage {
headers = append(headers, "page")
}
t := ui.NewTable(headers...)
now := runtime.ChainHeight()
for _, it := range items {
mark := ""
if it.Thread.Pinned(now) {
mark = "π"
}
cells := []string{
mark,
// The link title is the id, never the body: md.Link escapes
// markdown but not a pipe, and a pipe in a table cell opens a
// column. ui.Cell is the only thing that rewrites it.
md.Link("#"+it.ID.String(), th.ThreadURL(realmPath, it.ID)),
ui.Cell(ui.ShortN(it.Thread.Body, th.ExcerptLen, 0)),
ui.Addr(it.Thread.Author),
strconv.Itoa(len(it.Thread.Replies)),
}
if withPage {
cells = append(cells, ui.Cell(it.Thread.Page))
}
t.Row(cells...)
}
return t.String()
}
threads.gno
// Package threads is a discussion block any realm can embed, keyed on the page
// it appears on rather than on the realm that stores it.
//
// It is the text half of gno.land/r/moul/reactions: the same embed shape, the
// same page keys, two lines in the host realm.
//
// import "gno.land/r/moul/x/social/threads/v0"
//
// func Render(path string) string {
// return body + threads.RenderBlock()
// }
//
// [RenderBlock] takes no argument because it does not need one: a plain read
// exported by a realm and called by another opens no realm frame, so
// unsafe.CurrentRealm() inside it reports the CALLER. The host realm's own
// path is the page key, and nothing has to be configured or registered.
// [RenderBlockFor] is the explicit form, for a realm that renders more than
// one page or already holds its path as a constant.
//
// # The token, and the three things it has to answer
//
// THREAD exists because placement is the one thing a discussion has that
// people want and cannot all have at once.
//
// mint 1 THREAD to a thread's author, the first time each distinct
// address replies to it. People, not messages, and never yourself.
// sink [Boost] burns PinCost THREAD to pin a thread to the top of its
// page for PinBlocks blocks. That is the only thing that removes
// supply, and the only thing the token does.
// buyer anyone who wants placement and has not earned it. They have to
// acquire THREAD from someone who did, with [Transfer], which is
// what makes attention a market rather than a scoreboard.
//
// It is farmable, and saying so is cheaper than pretending otherwise: two
// addresses replying to each other mint one THREAD each per thread. The fix is
// a gate on who counts as a replier, which belongs in a vouching realm and not
// here; until then the cost of farming is one transaction per point and the
// benefit is capped by what a pin is worth.
package threads
import (
"chain"
"chain/runtime"
"chain/runtime/unsafe"
"strconv"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/store/v0"
sc "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/coin/v0"
th "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/threads/v0"
"gno.land/r/nt/grc20reg/v0"
)
// realmPath is this realm's own path, the one its gnomod.toml module line
// declares. It is written out rather than read from unsafe.CurrentRealm(),
// which reports the CALLER in every plain read this realm exports and would
// therefore build every link against whichever realm embedded the block.
const realmPath = "gno.land/r/moul/x/social/threads/v0"
const (
// EarnPerReplier is minted to a thread's author the first time each
// distinct address replies to it.
EarnPerReplier = int64(1)
// PinCost is burned by Boost, and PinBlocks is how long the pin lasts.
// A pin extends from whichever is later, now or the current pin, so
// buying one never shortens somebody else's.
PinCost = int64(10)
PinBlocks = int64(1000)
// BlockThreads is how many threads an embedded block shows before it
// turns into a link to the full page.
BlockThreads = 5
)
var (
// board holds every thread. A redeploy would wipe it, which is why this
// realm is not private (see gnomod.toml).
board = th.NewBoard()
// points is the THREAD ledger. The Coin is unexported on purpose: it
// carries unrestricted mint and burn, and an exported pointer to it
// would hand both to any importer.
points *sc.Coin
// tokenKey is the r/nt/grc20reg lookup key, which is how a realm that
// does not import this one refers to THREAD.
tokenKey string
)
// tokenPolicy is the three declarations THREAD is issued under. It is a var
// and not three literals inside init so that the tests, which rebuild the
// ledger between cases, issue the same token the chain holds.
var tokenPolicy = sc.Policy{
Mint: "1 to a thread's author per distinct address that replies to it",
Sink: "burned by Boost to pin a thread to the top of its page",
Buyer: "anyone who wants placement and has not earned it",
}
func init(cur realm) {
points = sc.New("Thread Points", "THREAD", 0, 0, tokenPolicy, 0, cur)
tokenKey = grc20reg.Register(cross(cur), points.Token(), "thread")
}
// Post opens a thread under page.
//
// page is a package path, the full one: "gno.land/r/moul/home". It does not
// have to be a realm that embeds the block, and nothing checks that it exists.
// A page is just a name, which is what lets a realm key discussion on
// something finer than itself.
func Post(cur realm, page, body string) int64 {
who := caller(cur)
id, err := board.Post(page, who, body, runtime.ChainHeight())
if err != nil {
panic(err.Error())
}
chain.Emit("Post", "id", id.String(), "page", page, "author", who.String())
return int64(id)
}
// Reply appends to a thread.
//
// The first time each distinct address replies to a given thread, its author
// earns EarnPerReplier. Replying again earns nothing, and replying to your own
// thread never earns anything.
func Reply(cur realm, threadID int64, body string) {
who := caller(cur)
id := store.ID(threadID)
isNew, err := board.Reply(id, who, body, runtime.ChainHeight())
if err != nil {
panic(err.Error())
}
chain.Emit("Reply", "id", id.String(), "author", who.String())
if isNew {
t, _ := board.Get(id)
points.Earn(t.Author, EarnPerReplier)
chain.Emit("Earn", "id", id.String(), "author", t.Author.String())
}
}
// Boost burns PinCost THREAD from the caller and pins the thread to the top of
// its page for PinBlocks blocks.
//
// Anyone may boost anyone's thread. The pin is on the thread and not on the
// buyer, so the thing being sold is placement and not authorship.
func Boost(cur realm, threadID int64) {
who := caller(cur)
id := store.ID(threadID)
t, ok := board.Get(id)
if !ok {
panic(th.ErrNoThread.Error())
}
now := runtime.ChainHeight()
from := now
if t.PinnedUntil > from {
from = t.PinnedUntil
}
// Charge first, pin second. The chain would revert both on an abort, so
// the order is invisible on mainnet and load-bearing everywhere else: a
// test, a filetest and any future caller that recovers see a refused
// boost that pinned nothing.
points.Spend(who, PinCost)
if err := board.Pin(id, from+PinBlocks); err != nil {
panic(err.Error())
}
chain.Emit("Boost", "id", id.String(), "by", who.String(),
"until", strconv.FormatInt(from+PinBlocks, 10))
}
// Transfer moves the caller's own THREAD. It is what makes the sink a market:
// somebody who wants a pin and has written nothing has to buy from an author.
func Transfer(cur realm, to address, amount int64) {
if err := points.CallerTeller().Transfer(0, cur, to, amount); err != nil {
panic(err.Error())
}
}
// Approve lets spender draw amount of the caller's THREAD.
func Approve(cur realm, spender address, amount int64) {
if err := points.CallerTeller().Approve(0, cur, spender, amount); err != nil {
panic(err.Error())
}
}
// TransferFrom spends an allowance the caller was granted.
func TransferFrom(cur realm, from, to address, amount int64) {
if err := points.CallerTeller().TransferFrom(0, cur, from, to, amount); err != nil {
panic(err.Error())
}
}
// RenderBlock returns the block for the realm CALLING it, which is the form a
// host realm embeds.
//
// It has no cur realm parameter on purpose. A plain read is borrowed: gno
// opens no realm frame for it, so unsafe.CurrentRealm() reports the caller's
// path and the block keys itself with no argument. Adding a cur realm here
// would silently reverse that and key every embed to this realm instead.
func RenderBlock() string {
return blockFor(unsafe.CurrentRealm().PkgPath())
}
// RenderBlockFor is [RenderBlock] for a named page. Use it from a crossing
// function, where there is no caller to read off the stack, or when one realm
// renders several pages.
func RenderBlockFor(page string) string { return blockFor(page) }
// blockFor is the shared body, so no exported read of this realm calls another
// and picks up the wrong path.
func blockFor(page string) string {
now := runtime.ChainHeight()
return th.Block(realmPath, page, board.List(page, now, BlockThreads), board.PageLen(page), now)
}
// Count is how many threads a page holds.
func Count(page string) int { return board.PageLen(page) }
// Total is how many threads exist, across every page.
func Total() int { return board.Len() }
// Pages is how many pages have ever been posted on.
func Pages() int { return board.Pages() }
// Repliers is how many distinct addresses have replied to a thread, which is
// also how much its author has earned from it.
func Repliers(threadID int64) int {
t, _ := board.Get(store.ID(threadID))
return t.Repliers()
}
// PinnedUntil is the height a thread stops being pinned at, or 0.
func PinnedUntil(threadID int64) int64 {
t, ok := board.Get(store.ID(threadID))
if !ok {
return 0
}
return t.PinnedUntil
}
// BalanceOf is an address's THREAD balance.
func BalanceOf(owner address) int64 { return points.BalanceOf(owner) }
// Allowance is what owner let spender draw.
func Allowance(owner, spender address) int64 {
return points.Token().Allowance(owner, spender)
}
// TotalSupply is the THREAD in existence: everything earned, less everything
// burned by Boost.
func TotalSupply() int64 { return points.Supply() }
// TokenKey is the r/nt/grc20reg key for THREAD.
func TokenKey() string { return tokenKey }
// caller is the address that called us, checked the one way that is safe.
func caller(cur realm) address {
if !cur.IsCurrent() {
panic("spoofed realm: cur is not the live crossing frame")
}
return cur.Previous().Address()
}
threads_test.gno
package threads
import (
"strconv"
"strings"
"testing"
sc "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/coin/v0"
th "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/social/threads/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
const homePage = "gno.land/r/moul/home"
var (
alice = testutils.TestAddress("alice")
bob = testutils.TestAddress("bob")
carol = testutils.TestAddress("carol")
)
// reset clears realm state. Realm globals live for the whole test binary, so
// everything a later test reads, including the ledger, starts here.
//
// The ledger is rebuilt through a same-realm cross because grc20.NewToken
// needs a code-realm frame, which a test's EOA-origin cur is not. It is NOT
// re-registered with grc20reg: the registry is another realm and its entry
// survives this one's state.
func reset(cur realm) {
board = th.NewBoard()
func(cur realm) { // the name is forced: a realm argument must be called cur
points = sc.New("Thread Points", "THREAD", 0, 0, tokenPolicy, 0, cur)
}(cross(cur))
}
// earn gives who n THREAD the only way the realm allows: n distinct addresses
// replying to a thread they wrote.
func earn(cur realm, t *testing.T, who address, n int) int64 {
t.Helper()
testing.SetRealm(testing.NewUserRealm(who))
id := Post(cross(cur), homePage, "a thread by "+who.String())
for i := 0; i < n; i++ {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("replier" + strconv.Itoa(i))))
Reply(cross(cur), id, "hello")
}
return id
}
func TestAnAuthorEarnsPeopleAndNotMessages(cur realm, t *testing.T) {
reset(cur)
testing.SetRealm(testing.NewUserRealm(alice))
id := Post(cross(cur), homePage, "first thread")
uassert.Equal(t, int64(0), BalanceOf(alice), "writing earns nothing on its own")
testing.SetRealm(testing.NewUserRealm(bob))
Reply(cross(cur), id, "nice")
uassert.Equal(t, int64(1), BalanceOf(alice))
testing.SetRealm(testing.NewUserRealm(bob))
Reply(cross(cur), id, "still me")
uassert.Equal(t, int64(1), BalanceOf(alice), "one person is one point, however much they say")
testing.SetRealm(testing.NewUserRealm(alice))
Reply(cross(cur), id, "thanks")
uassert.Equal(t, int64(1), BalanceOf(alice), "replying to yourself is not an audience")
testing.SetRealm(testing.NewUserRealm(carol))
Reply(cross(cur), id, "hi")
uassert.Equal(t, int64(2), BalanceOf(alice))
uassert.Equal(t, 2, Repliers(id))
uassert.Equal(t, int64(2), TotalSupply())
uassert.Equal(t, int64(0), BalanceOf(bob), "a replier earns nothing")
}
func TestBoostIsTheOnlyThingThatBurns(cur realm, t *testing.T) {
reset(cur)
id := earn(cur, t, alice, 10)
urequire.Equal(t, int64(10), BalanceOf(alice))
testing.SetRealm(testing.NewUserRealm(alice))
Boost(cross(cur), id)
uassert.Equal(t, int64(0), BalanceOf(alice))
uassert.Equal(t, int64(0), TotalSupply(), "the sink removes supply, it does not move it")
uassert.Equal(t, int64(123+PinBlocks), PinnedUntil(id), "tests start at height 123")
}
func TestBoostRefusesWhatTheCallerCannotAfford(cur realm, t *testing.T) {
reset(cur)
id := earn(cur, t, alice, 1)
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "balance 1 is short of 10", func() {
Boost(cross(cur), id)
})
uassert.Equal(t, int64(0), PinnedUntil(id), "a refused boost pins nothing")
uassert.Equal(t, int64(1), BalanceOf(alice))
}
// A second boost extends from the current pin, not from now, so the thread
// never loses time it was already paid for.
func TestASecondBoostExtendsRatherThanRestarts(cur realm, t *testing.T) {
reset(cur)
id := earn(cur, t, alice, 20)
testing.SetRealm(testing.NewUserRealm(alice))
Boost(cross(cur), id)
first := PinnedUntil(id)
testing.SetRealm(testing.NewUserRealm(alice))
Boost(cross(cur), id)
uassert.Equal(t, first+PinBlocks, PinnedUntil(id))
uassert.Equal(t, int64(0), BalanceOf(alice))
}
// Anyone may boost anyone's thread, and the buyer has to get THREAD from
// somebody who earned it. That is the whole market.
func TestPlacementIsBoughtFromAnEarner(cur realm, t *testing.T) {
reset(cur)
id := earn(cur, t, alice, 10)
testing.SetRealm(testing.NewUserRealm(alice))
Transfer(cross(cur), bob, 10)
uassert.Equal(t, int64(0), BalanceOf(alice))
uassert.Equal(t, int64(10), BalanceOf(bob))
testing.SetRealm(testing.NewUserRealm(bob))
Boost(cross(cur), id)
uassert.True(t, PinnedUntil(id) > 0, "bob pinned alice's thread")
uassert.Equal(t, int64(0), TotalSupply())
}
func TestPostRefusals(cur realm, t *testing.T) {
reset(cur)
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "not a page key", func() {
Post(cross(cur), "nopath", "body")
})
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "body is empty", func() {
Post(cross(cur), homePage, " ")
})
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "no such thread", func() {
Reply(cross(cur), 99, "into the void")
})
uassert.Equal(t, 0, Total())
}
func TestCountsAreScopedToTheirPage(cur realm, t *testing.T) {
reset(cur)
testing.SetRealm(testing.NewUserRealm(alice))
Post(cross(cur), homePage, "on home")
testing.SetRealm(testing.NewUserRealm(alice))
Post(cross(cur), "gno.land/r/moul/blog", "on the blog")
uassert.Equal(t, 1, Count(homePage))
uassert.Equal(t, 0, Count("gno.land/r/nobody/here"))
uassert.Equal(t, 2, Total())
uassert.Equal(t, 2, Pages())
}
// RenderBlockFor is the embed, and it escapes what it shows: a raw pipe in a
// body would otherwise open a column in the host realm's page.
func TestRenderBlockForEscapesTheBody(cur realm, t *testing.T) {
reset(cur)
testing.SetRealm(testing.NewUserRealm(alice))
Post(cross(cur), homePage, "a | pipe")
got := RenderBlockFor(homePage)
uassert.True(t, strings.Contains(got, "func=Post"), "the block offers the transaction: "+got)
uassert.True(t, strings.Contains(got, `| a \| pipe |`),
"the body cell escapes the pipe rather than opening a column: "+got)
uassert.False(t, strings.Contains(got, "| a | pipe"), "no raw pipe survives: "+got)
uassert.True(t, strings.Contains(RenderBlockFor("gno.land/r/nobody/here"), "No discussion yet."))
}
// TestRender uses uassert rather than an Example because every view contains
// consecutive blank lines, which gno collapses inside an // Output: block.
func TestRender(cur realm, t *testing.T) {
reset(cur)
testing.SetRealm(testing.NewUserRealm(alice))
id := Post(cross(cur), homePage, "a thread about [links](x)")
testing.SetRealm(testing.NewUserRealm(bob))
Reply(cross(cur), id, "a reply with a | pipe")
index := Render("")
uassert.True(t, strings.Contains(index, "| 1 | 1 | 1 |"), "threads, pages, supply: "+index)
uassert.True(t, strings.Contains(index, tokenPolicy.Sink), "the index declares the sink")
uassert.True(t, strings.Contains(index, `import "`+realmPath+`"`), "the index is the embed doc")
page := Render("page/" + homePage)
uassert.True(t, strings.Contains(page, "/r/moul/home"), "it links the page itself: "+page)
uassert.True(t, strings.Contains(page, "func=Post"))
sid := strconv.FormatInt(id, 10)
thread := Render("thread/" + sid)
uassert.True(t, strings.Contains(thread, "# Thread #"+sid))
uassert.True(t, strings.Contains(thread, "a thread about \\[links\\]\\(x\\)"),
"the body is escaped where it is shown: "+thread)
uassert.True(t, strings.Contains(thread, "a reply with a \\| pipe"),
"a reply cell cannot open a column: "+thread)
uassert.True(t, strings.Contains(thread, "func=Boost"))
uassert.Equal(t, "# Threads\nNo thread #4242", Render("thread/4242"))
uassert.Equal(t, "# Threads\nNot a thread id: nope", Render("thread/nope"))
uassert.Equal(t, "# Threads\nNot a page key: nope", Render("page/nope"))
uassert.True(t, strings.HasPrefix(Render("elsewhere"), "# Not found"))
}
func TestTokenIsDiscoverableWithoutImportingThisRealm(t *testing.T) {
uassert.True(t, strings.HasSuffix(TokenKey(), ".THREAD"), TokenKey())
uassert.True(t, strings.Contains(TokenKey(), realmPath), TokenKey())
}