|
| 1 | +package veun_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "html/template" |
| 6 | + "testing" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/alecthomas/assert/v2" |
| 10 | + |
| 11 | + . "github.com/stanistan/veun" |
| 12 | +) |
| 13 | + |
| 14 | +type ExpensiveViewData struct { |
| 15 | + Title string `json:"title"` |
| 16 | +} |
| 17 | + |
| 18 | +var expensiveViewTpl = MustParseTemplate("expensiveView", `{{ .Title }} success`) |
| 19 | + |
| 20 | +type ExpensiveView struct { |
| 21 | + Data chan ExpensiveViewData |
| 22 | + Err chan error |
| 23 | +} |
| 24 | + |
| 25 | +func NewExpensiveView(shouldErr bool) *ExpensiveView { |
| 26 | + errCh := make(chan error) |
| 27 | + dataCh := make(chan ExpensiveViewData) |
| 28 | + |
| 29 | + go func() { |
| 30 | + defer func() { |
| 31 | + close(errCh) |
| 32 | + close(dataCh) |
| 33 | + }() |
| 34 | + |
| 35 | + // do data fetching and either write to |
| 36 | + // one thing or the other |
| 37 | + time.Sleep(1 * time.Millisecond) |
| 38 | + if shouldErr { |
| 39 | + errCh <- fmt.Errorf("fetch failed") |
| 40 | + } else { |
| 41 | + dataCh <- ExpensiveViewData{Title: "hi"} |
| 42 | + } |
| 43 | + }() |
| 44 | + |
| 45 | + return &ExpensiveView{Data: dataCh, Err: errCh} |
| 46 | +} |
| 47 | + |
| 48 | +func (v *ExpensiveView) Renderable() (Renderable, error) { |
| 49 | + select { |
| 50 | + case err := <-v.Err: |
| 51 | + return nil, err |
| 52 | + case data := <-v.Data: |
| 53 | + return View{Tpl: expensiveViewTpl, Data: data}, nil |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +func TestViewWithChannels(t *testing.T) { |
| 58 | + t.Run("successful", func(t *testing.T) { |
| 59 | + html, err := Render(NewExpensiveView(false)) |
| 60 | + assert.NoError(t, err) |
| 61 | + assert.Equal(t, template.HTML(`hi success`), html) |
| 62 | + }) |
| 63 | + |
| 64 | + t.Run("failed", func(t *testing.T) { |
| 65 | + _, err := Render(NewExpensiveView(true)) |
| 66 | + assert.Error(t, err) |
| 67 | + }) |
| 68 | +} |
0 commit comments