go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/viewutil/form_for_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package viewutil
     9  
    10  import (
    11  	"html/template"
    12  	"testing"
    13  
    14  	"go.charczuk.com/sdk/assert"
    15  )
    16  
    17  type formForTest struct {
    18  	Name     string
    19  	Location string `form:"label='Location of the thing'"`
    20  	Age      int
    21  	Ready    bool
    22  }
    23  
    24  type formForProviderTest struct {
    25  	Name string
    26  }
    27  
    28  func (f formForProviderTest) Form(action string) template.HTML {
    29  	return template.HTML(f.Name)
    30  }
    31  
    32  func Test_FormFor(t *testing.T) {
    33  	obj := formForTest{
    34  		Name:     "hello",
    35  		Location: "San Francisco, CA",
    36  		Age:      32,
    37  		Ready:    true,
    38  	}
    39  
    40  	formFor := FormFor(obj, "/doingthangs")
    41  	expected := `<form method="POST" data-form-for="formForTest" action="/doingthangs">
    42  <input name="Name" type="text" value="hello"/>
    43  <label for="Location">Location of the thing</label><input name="Location" type="text" value="San Francisco, CA"/>
    44  <input name="Age" type="number" value="32"/>
    45  <input name="Ready" type="checkbox" checked/>
    46  <input type="submit">Submit</input>
    47  </form>`
    48  	assert.ItsEqual(t, expected, formFor)
    49  }
    50  
    51  func Test_FormFor_FormProvider(t *testing.T) {
    52  	obj := formForProviderTest{
    53  		Name: "hello",
    54  	}
    55  
    56  	formFor := FormFor(obj, "/doingthangs")
    57  	assert.ItsEqual(t, "hello", string(formFor))
    58  }
    59  
    60  func Test_ControlFor(t *testing.T) {
    61  	obj := formForTest{
    62  		Name: "hello",
    63  	}
    64  	controlFor := ControlFor(obj, "Name")
    65  	assert.ItsEqual(t, `<input name="Name" type="text" value="hello"/>`, string(controlFor))
    66  }
    67  
    68  func Test_ControlFor_wrongName(t *testing.T) {
    69  	obj := formForTest{
    70  		Name: "hello",
    71  	}
    72  	controlFor := ControlFor(obj, "NotName")
    73  	assert.ItsEmpty(t, string(controlFor))
    74  }