コード例 #1
0
ファイル: web_context_test.go プロジェクト: MG-RAST/Shock
func TestRequestData(t *testing.T) {

	responseWriter := new(http_test.TestResponseWriter)
	testRequest, _ := http.NewRequest("GET", "http://goweb.org/people/123", strings.NewReader("{\"something\":true}"))

	codecService := codecsservices.NewWebCodecService()

	c := NewWebContext(responseWriter, testRequest, codecService)

	bod, _ := c.RequestBody()
	assert.Equal(t, "{\"something\":true}", string(bod))
	dat, datErr := c.RequestData()

	if assert.NoError(t, datErr) {
		assert.Equal(t, true, dat.(map[string]interface{})["something"])
	}

	responseWriter = new(http_test.TestResponseWriter)
	testRequest, _ = http.NewRequest("GET", "http://goweb.org/people/123?body={\"something\":true}", nil)

	codecService = codecsservices.NewWebCodecService()

	c = NewWebContext(responseWriter, testRequest, codecService)

	bod, _ = c.RequestBody()
	assert.Equal(t, "{\"something\":true}", string(bod))
	dat, datErr = c.RequestData()

	if assert.NoError(t, datErr) {
		assert.Equal(t, true, dat.(map[string]interface{})["something"])
	}

}
コード例 #2
0
func TestMarshalAndUnmarshal(t *testing.T) {

	// make a big object
	obj := map[string]interface{}{}
	obj["name"] = "Mat"
	obj["age"] = 30
	obj["address"] = map[string]interface{}{
		"street":  "Pearl Street",
		"city":    "Boulder",
		"state":   "CO",
		"country": "USA",
	}
	obj["animals"] = map[string]interface{}{
		"favourite": []string{"Dog", "Cat"},
	}

	bytes, marshalErr := xmlCodec.Marshal(obj, nil)

	if assert.NoError(t, marshalErr) {
		assert.Contains(t, string(bytes), "<?xml version=\"1.0\"?>", "Output")
	}

	// unmarshal it
	var newObj interface{}
	if assert.NoError(t, xmlCodec.Unmarshal(bytes, &newObj)) {

		assert.NotNil(t, newObj)

	}

}
コード例 #3
0
func TestUnmarshal_arrayOfMaps(t *testing.T) {

	xml := `<objects><object><name>Mat</name><age type="int">30</age><yesOrNo type="bool">true</yesOrNo><address><city>Boulder</city><state>CO</state></address></object><object><name>Tyler</name><age type="int">28</age><yesOrNo type="bool">false</yesOrNo><address><city>Salt Lake City</city><state>UT</state></address></object></objects>`

	obj, err := unmarshal(xml, nil)

	if assert.NoError(t, err) {
		if assert.NotNil(t, obj) {

			os := obj.([]interface{})

			o1 := os[0].(map[string]interface{})
			assert.Equal(t, "Mat", o1["name"])
			assert.Equal(t, 30, o1["age"])
			assert.Equal(t, true, o1["yesOrNo"])

			o2 := os[1].(map[string]interface{})
			assert.Equal(t, "Tyler", o2["name"])
			assert.Equal(t, 28, o2["age"])
			assert.Equal(t, false, o2["yesOrNo"])

		}
	}

}
コード例 #4
0
ファイル: accept_test.go プロジェクト: MG-RAST/Shock
func TestParseAccept_NoParams(t *testing.T) {
	acceptString := "application/json"
	accept, err := ParseAcceptEntry(acceptString)
	assert.NoError(t, err, acceptString+" should parse with no errors")
	assert.Equal(t, acceptString, accept.ContentType.MimeType)
	assert.Equal(t, accept.Quality, 1.0)
}
コード例 #5
0
ファイル: accept_test.go プロジェクト: MG-RAST/Shock
func TestParseAccept_QualityParam(t *testing.T) {
	acceptString := "application/json; q=0.4"
	expectedQuality := 0.4

	accept, err := ParseAcceptEntry(acceptString)
	assert.NoError(t, err, acceptString+" should parse with no errors")
	assert.Equal(t, accept.Quality, expectedQuality)
}
コード例 #6
0
ファイル: map_test.go プロジェクト: MG-RAST/Shock
func TestMapFromURLQuery(t *testing.T) {

	m, err := FromURLQuery("name=tyler&state=UT")
	if assert.NoError(t, err) && assert.NotNil(t, m) {
		assert.Equal(t, "tyler", m.Get("name").Str())
		assert.Equal(t, "UT", m.Get("state").Str())
	}

}
コード例 #7
0
func TestMarshal_map(t *testing.T) {

	data := map[string]interface{}{"name": "Mat", "age": 30, "yesOrNo": true}
	bytes, marshalErr := marshal(data, false, 0, nil)

	if assert.NoError(t, marshalErr) {
		assert.Equal(t, "<object><name>Mat</name><age>30</age><yesOrNo>true</yesOrNo></object>", string(bytes), "Output")
	}

}
コード例 #8
0
ファイル: accept_test.go プロジェクト: MG-RAST/Shock
func TestOrderAcceptHeader_EqualQualityAndSpecificity(t *testing.T) {
	expectedOrder := []string{"application/json", "application/xml", "text/xml"}
	header := strings.Join(expectedOrder, ", ")
	orderedAccept, err := OrderAcceptHeader(header)
	assert.NoError(t, err)
	for index, expectedType := range expectedOrder {
		entry := orderedAccept[index]
		assert.Equal(t, entry.ContentType.MimeType, expectedType)
	}
}
コード例 #9
0
func TestWrapCodec_Marshal(t *testing.T) {
	codec := new(testCodec)
	testContentType := "application/vnd.stretchr.test+json"
	wrappedCodec := wrapCodecWithContentType(codec, testContentType)

	response, err := wrappedCodec.Marshal(nil, nil)
	assert.NoError(t, err)
	expectedResponse := `{"matched_type":"` + testContentType + `"}`
	assert.Equal(t, response, []byte(expectedResponse),
		"The wrapped codec should add the matched content type to options on unmarshal")
}
コード例 #10
0
func TestMarshal_mapWithTypes(t *testing.T) {

	data := map[string]interface{}{"name": "Mat", "age": 30, "yesOrNo": true}
	options := objx.MSI(OptionIncludeTypeAttributes, true)
	bytes, marshalErr := marshal(data, false, 0, options)

	if assert.NoError(t, marshalErr) {
		assert.Equal(t, "<object><name type=\"string\">Mat</name><age type=\"int\">30</age><yesOrNo type=\"bool\">true</yesOrNo></object>", string(bytes), "Output")
	}

}
コード例 #11
0
ファイル: conversions_test.go プロジェクト: MG-RAST/Shock
func TestConversionBase64(t *testing.T) {

	o := New(map[string]interface{}{"name": "Mat"})

	result, err := o.Base64()

	if assert.NoError(t, err) {
		assert.Equal(t, "eyJuYW1lIjoiTWF0In0=", result)
	}

	assert.Equal(t, "eyJuYW1lIjoiTWF0In0=", o.MustBase64())

}
コード例 #12
0
ファイル: map_test.go プロジェクト: MG-RAST/Shock
func TestMapFromBase64String(t *testing.T) {

	base64String := "eyJuYW1lIjoiTWF0In0="

	o, err := FromBase64(base64String)

	if assert.NoError(t, err) {
		assert.Equal(t, o.Get("name").Str(), "Mat")
	}

	assert.Equal(t, MustFromBase64(base64String).Get("name").Str(), "Mat")

}
コード例 #13
0
ファイル: map_test.go プロジェクト: MG-RAST/Shock
func TestMapFromSignedBase64String(t *testing.T) {

	base64String := "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6"

	o, err := FromSignedBase64(base64String, "key")

	if assert.NoError(t, err) {
		assert.Equal(t, o.Get("name").Str(), "Mat")
	}

	assert.Equal(t, MustFromSignedBase64(base64String, "key").Get("name").Str(), "Mat")

}
コード例 #14
0
ファイル: conversions_test.go プロジェクト: MG-RAST/Shock
func TestConversionSignedBase64(t *testing.T) {

	o := New(map[string]interface{}{"name": "Mat"})

	result, err := o.SignedBase64("key")

	if assert.NoError(t, err) {
		assert.Equal(t, "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6", result)
	}

	assert.Equal(t, "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6", o.MustSignedBase64("key"))

}
コード例 #15
0
func TestMarshal_arrayOfMaps(t *testing.T) {

	data1 := map[string]interface{}{"name": "Mat"}
	data2 := map[string]interface{}{"name": "Tyler"}
	data3 := map[string]interface{}{"name": "Ryan"}
	array := []map[string]interface{}{data1, data2, data3}
	bytes, marshalErr := marshal(array, false, 0, nil)

	if assert.NoError(t, marshalErr) {
		assert.Equal(t, "<objects><object><name>Mat</name></object><object><name>Tyler</name></object><object><name>Ryan</name></object></objects>", string(bytes), "Output")
	}

}
コード例 #16
0
ファイル: mapping_test.go プロジェクト: MG-RAST/Shock
func TestMapStatic(t *testing.T) {

	codecService := codecsservices.NewWebCodecService()
	h := NewHttpHandler(codecService)

	h.MapStatic("/static", "/location/of/static")

	assert.Equal(t, 1, len(h.HandlersPipe()))

	staticHandler := h.HandlersPipe()[0].(*PathMatchHandler)

	if assert.Equal(t, 1, len(staticHandler.HttpMethods)) {
		assert.Equal(t, goweb_http.MethodGet, staticHandler.HttpMethods[0])
	}

	var ctx context.Context
	var willHandle bool

	ctx = context_test.MakeTestContextWithPath("/static/some/deep/file.dat")
	willHandle, _ = staticHandler.WillHandle(ctx)
	assert.True(t, willHandle, "Static handler should handle")

	ctx = context_test.MakeTestContextWithPath("/static/../static/some/deep/file.dat")
	willHandle, _ = staticHandler.WillHandle(ctx)
	assert.True(t, willHandle, "Static handler should handle")

	ctx = context_test.MakeTestContextWithPath("/static/some/../file.dat")
	willHandle, _ = staticHandler.WillHandle(ctx)
	assert.True(t, willHandle, "Static handler should handle")

	ctx = context_test.MakeTestContextWithPath("/static/../file.dat")
	willHandle, _ = staticHandler.WillHandle(ctx)
	assert.False(t, willHandle, "Static handler should not handle")

	ctx = context_test.MakeTestContextWithPath("/static")
	willHandle, _ = staticHandler.WillHandle(ctx)
	assert.True(t, willHandle, "Static handler should handle")

	ctx = context_test.MakeTestContextWithPath("/static/")
	willHandle, _ = staticHandler.WillHandle(ctx)
	assert.True(t, willHandle, "Static handler should handle")

	ctx = context_test.MakeTestContextWithPath("/static/doc.go")
	willHandle, _ = staticHandler.WillHandle(ctx)
	_, staticHandleErr := staticHandler.Handle(ctx)

	if assert.NoError(t, staticHandleErr) {

	}

}
コード例 #17
0
ファイル: conversions_test.go プロジェクト: MG-RAST/Shock
func TestConversionJSON(t *testing.T) {

	jsonString := `{"name":"Mat"}`
	o := MustFromJSON(jsonString)

	result, err := o.JSON()

	if assert.NoError(t, err) {
		assert.Equal(t, jsonString, result)
	}

	assert.Equal(t, jsonString, o.MustJSON())

}
コード例 #18
0
ファイル: accept_test.go プロジェクト: MG-RAST/Shock
// AcceptTree.Flatten should always allocate exactly as much memory as
// it needs.  If capacity and length of the return value are not
// equal, something is wrong.
func TestOrderAcceptHeader_FlattenPerformance(t *testing.T) {
	testHeaders := []string{
		"",
		"application/json",
		"application/xml; q=0.7, */*; q=0.1, text/*; q=0.1, application/json, text/xml; q=0.7",
	}

	for _, testHeader := range testHeaders {
		orderedAccept, err := OrderAcceptHeader(testHeader)
		assert.NoError(t, err)
		assert.Equal(t, len(orderedAccept), cap(orderedAccept),
			"Flatten should allocate exactly as much memory as it needs; failed header: "+testHeader)
	}
}
コード例 #19
0
// https://github.com/stretchr/goweb/issues/20
func TestWriteResponseObject_ContentNegotiation_HasCallback(t *testing.T) {

	http := new(GowebHTTPResponder)
	codecService := codecsservices.NewWebCodecService()
	API := NewGowebAPIResponder(codecService, http)
	ctx := context_test.MakeTestContext()
	ctx.HttpRequest().URL, _ = url.Parse("http://stretchr.org/something?callback=doSomething")
	data := map[string]interface{}{"name": "Mat"}

	API.WriteResponseObject(ctx, 200, data)

	// get the expected output
	codec, codecErr := codecService.GetCodec("text/javascript")
	if assert.NoError(t, codecErr) {

		expectedOutput, marshalErr := codec.Marshal(data, map[string]interface{}{"options.client.callback": "doSomething"})
		if assert.NoError(t, marshalErr) {
			assert.Equal(t, []byte(context_test.TestResponseWriter.Output), expectedOutput)
		}

	}

}
コード例 #20
0
ファイル: csv_codec_test.go プロジェクト: MG-RAST/Shock
func TestMarshal_SingleObject(t *testing.T) {

	obj := map[string]interface{}{"field1": "one", "field2": "two", "field3": "three"}

	csvCodec := new(CsvCodec)
	bytes, marshalErr := csvCodec.Marshal(obj, nil)

	if assert.NoError(t, marshalErr) {

		assert.Equal(t, "field1,field2,field3\n\"\"\"one\"\"\",\"\"\"two\"\"\",\"\"\"three\"\"\"\n", string(bytes))

	}

}
コード例 #21
0
// https://github.com/stretchr/goweb/issues/20
func TestWriteResponseObject_ContentNegotiation_FileExtension(t *testing.T) {

	http := new(GowebHTTPResponder)
	codecService := codecsservices.NewWebCodecService()
	API := NewGowebAPIResponder(codecService, http)
	ctx := context_test.MakeTestContext()
	ctx.HttpRequest().URL, _ = url.Parse("http://stretchr.org/something.msgpack")
	data := map[string]interface{}{"name": "Mat"}

	API.WriteResponseObject(ctx, 200, data)

	// get the expected output
	codec, codecErr := codecService.GetCodec("application/x-msgpack")
	if assert.NoError(t, codecErr) {

		expectedOutput, marshalErr := codec.Marshal(data, nil)
		if assert.NoError(t, marshalErr) {
			assert.Equal(t, []byte(context_test.TestResponseWriter.Output), expectedOutput)
		}

	}

}
コード例 #22
0
ファイル: csv_codec_test.go プロジェクト: MG-RAST/Shock
func TestMarshal_ComplexMap(t *testing.T) {

	obj1 := map[string]interface{}{"name": "Mat", "age": 30, "language": "en"}
	obj2 := map[string]interface{}{"obj": obj1}
	obj3 := map[string]interface{}{"another_obj": obj2}

	csvCodec := new(CsvCodec)
	bytes, marshalErr := csvCodec.Marshal(obj3, nil)

	if assert.NoError(t, marshalErr) {

		assert.Equal(t, "another_obj\n\"{\"\"obj\"\":{\"\"age\"\":30,\"\"language\"\":\"\"en\"\",\"\"name\"\":\"\"Mat\"\"}}\"\n", string(bytes))

	}

}
コード例 #23
0
ファイル: csv_codec_test.go プロジェクト: MG-RAST/Shock
func TestMapFromFieldsAndRow(t *testing.T) {

	fields := []string{"field1", "field2", "field3"}
	row := []string{"one", "two", "three"}

	m, err := mapFromFieldsAndRow(fields, row)

	if assert.NoError(t, err) && assert.NotNil(t, m) {

		assert.Equal(t, "one", m["field1"])
		assert.Equal(t, "two", m["field2"])
		assert.Equal(t, "three", m["field3"])

	}

}
コード例 #24
0
ファイル: content_type_test.go プロジェクト: MG-RAST/Shock
func TestParseContentType_WithParams(t *testing.T) {
	contentTypeString := "application/xml; q=0.7; test=hello"
	expectedMimeType := "application/xml"
	expectedParams := map[string]string{
		"q":    "0.7",
		"test": "hello",
	}
	contentType, err := ParseContentType(contentTypeString)
	assert.NoError(t, err)
	assert.Equal(t, expectedMimeType, contentType.MimeType)
	for index, value := range expectedParams {
		parsedValue, ok := contentType.Parameters[index]
		assert.True(t, ok, "All expected values should have been parsed as params")
		assert.Equal(t, parsedValue, value)
	}
}
コード例 #25
0
ファイル: csv_codec_test.go プロジェクト: MG-RAST/Shock
func TestMarshal_MultipleObjects_WithDisimilarSchema(t *testing.T) {

	arr := make([]map[string]interface{}, 3)
	arr[0] = map[string]interface{}{"name": "Mat", "age": 30, "language": "en"}
	arr[1] = map[string]interface{}{"first_name": "Tyler", "age": 28, "last_name": "Bunnell"}
	arr[2] = map[string]interface{}{"name": "Ryan", "age": 26, "speaks": "english"}

	csvCodec := new(CsvCodec)
	bytes, marshalErr := csvCodec.Marshal(arr, nil)

	if assert.NoError(t, marshalErr) {

		assert.Equal(t, "name,age,language,first_name,last_name,speaks\n\"\"\"Mat\"\"\",30,\"\"\"en\"\"\",\"\",\"\",\"\"\n\"\",28,\"\",\"\"\"Tyler\"\"\",\"\"\"Bunnell\"\"\",\"\"\n\"\"\"Ryan\"\"\",26,\"\",\"\",\"\",\"\"\"english\"\"\"\n", string(bytes))

	}

}
コード例 #26
0
ファイル: csv_codec_test.go プロジェクト: MG-RAST/Shock
func TestMarshal_MultipleObjects(t *testing.T) {

	arr := make([]map[string]interface{}, 3)
	arr[0] = map[string]interface{}{"field1": "oneA", "field2": "twoA", "field3": "threeA"}
	arr[1] = map[string]interface{}{"field1": "oneB", "field2": "twoB", "field3": "threeB"}
	arr[2] = map[string]interface{}{"field1": "oneC", "field2": "twoC", "field3": "threeC"}

	csvCodec := new(CsvCodec)
	bytes, marshalErr := csvCodec.Marshal(arr, nil)

	if assert.NoError(t, marshalErr) {

		assert.Equal(t, "field1,field2,field3\n\"\"\"oneA\"\"\",\"\"\"twoA\"\"\",\"\"\"threeA\"\"\"\n\"\"\"oneB\"\"\",\"\"\"twoB\"\"\",\"\"\"threeB\"\"\"\n\"\"\"oneC\"\"\",\"\"\"twoC\"\"\",\"\"\"threeC\"\"\"\n", string(bytes))

	}

}
コード例 #27
0
func TestUnmarshal_map(t *testing.T) {

	xml := `<object><name>Mat</name><age type='int'>30</age><yesOrNo type='bool'>true</yesOrNo><address><city>Boulder</city><state>CO</state></address></object>`

	obj, err := unmarshal(xml, nil)

	if assert.NoError(t, err) {
		if assert.NotNil(t, obj) {

			o := obj.(map[string]interface{})

			assert.Equal(t, "Mat", o["name"])
			assert.Equal(t, 30, o["age"])
			assert.Equal(t, true, o["yesOrNo"])

		}
	}

}
コード例 #28
0
ファイル: web_context_test.go プロジェクト: MG-RAST/Shock
func TestRequestData_ArrayOfData(t *testing.T) {

	responseWriter := new(http_test.TestResponseWriter)
	testRequest, _ := http.NewRequest("GET", "http://goweb.org/people/123", strings.NewReader("[{\"something\":true},{\"something\":false}]"))

	codecService := codecsservices.NewWebCodecService()

	c := NewWebContext(responseWriter, testRequest, codecService)

	bod, _ := c.RequestBody()
	assert.Equal(t, "[{\"something\":true},{\"something\":false}]", string(bod))
	dat, datErr := c.RequestData()

	if assert.NoError(t, datErr) {
		assert.NotNil(t, dat.([]interface{}))
		responseDataArray, _ := c.RequestDataArray()
		assert.Equal(t, dat.([]interface{}), responseDataArray)
	}

}
コード例 #29
0
ファイル: accept_test.go プロジェクト: MG-RAST/Shock
func TestOrderAcceptHeader_VariedQualityAndSpecificity(t *testing.T) {
	header := "application/xml; q=0.7, */*; q=0.1, text/*; q=0.1, application/json, text/xml; q=0.7"
	expectedOrder := []string{
		// Default quality should be 1.0, so json should be first.
		"application/json",

		// application/xml shows up in the list before text/xml and
		// they are at the same q value and the same specificity, so
		// application/xml should show up before text/xml.
		"application/xml",
		"text/xml",

		// text/* is more specific than */* and they are at the same q
		// value, so text/* should show up before */*.
		"text/*",
		"*/*",
	}
	orderedAccept, err := OrderAcceptHeader(header)
	assert.NoError(t, err)
	for index, expectedType := range expectedOrder {
		entry := orderedAccept[index]
		assert.Equal(t, entry.ContentType.MimeType, expectedType)
	}
}
コード例 #30
0
ファイル: content_type_test.go プロジェクト: MG-RAST/Shock
func TestParseContentType_NoParams(t *testing.T) {
	contentTypeString := "application/json"
	contentType, err := ParseContentType(contentTypeString)
	assert.NoError(t, err)
	assert.Equal(t, contentTypeString, contentType.MimeType)
}