...

Source file src/github.com/go-openapi/runtime/json_test.go

Documentation: github.com/go-openapi/runtime

     1  // Copyright 2015 go-swagger maintainers
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package runtime
    16  
    17  import (
    18  	"bytes"
    19  	"io"
    20  	"net/http/httptest"
    21  	"testing"
    22  
    23  	"github.com/stretchr/testify/assert"
    24  	"github.com/stretchr/testify/require"
    25  )
    26  
    27  var consProdJSON = `{"name":"Somebody","id":1}`
    28  
    29  type eofRdr struct {
    30  }
    31  
    32  func (r *eofRdr) Read(_ []byte) (int, error) {
    33  	return 0, io.EOF
    34  }
    35  
    36  func TestJSONConsumer(t *testing.T) {
    37  	cons := JSONConsumer()
    38  	var data struct {
    39  		Name string
    40  		ID   int
    41  	}
    42  	err := cons.Consume(bytes.NewBufferString(consProdJSON), &data)
    43  	require.NoError(t, err)
    44  	assert.Equal(t, "Somebody", data.Name)
    45  	assert.Equal(t, 1, data.ID)
    46  
    47  	err = cons.Consume(new(eofRdr), &data)
    48  	require.Error(t, err)
    49  }
    50  
    51  func TestJSONProducer(t *testing.T) {
    52  	prod := JSONProducer()
    53  	data := struct {
    54  		Name string `json:"name"`
    55  		ID   int    `json:"id"`
    56  	}{Name: "Somebody", ID: 1}
    57  
    58  	rw := httptest.NewRecorder()
    59  	err := prod.Produce(rw, data)
    60  	require.NoError(t, err)
    61  	assert.Equal(t, consProdJSON+"\n", rw.Body.String())
    62  }
    63  

View as plain text