github.com/unigraph-dev/dgraph@v1.1.1-0.20200923154953-8b52b426f765/types/geo_test.go (about)

     1  /*
     2   * Copyright 2016-2018 Dgraph Labs, Inc. and Contributors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package types
    18  
    19  import (
    20  	"reflect"
    21  	"testing"
    22  )
    23  
    24  func TestParse(t *testing.T) {
    25  	array := []string{
    26  		`{'type':'Point','coordinates':[1,2]}`,
    27  		`{'type':'MultiLineString','coordinates':[[[1,2,3],[4,5,6],[7,8,9],[1,2,3]]]}`,
    28  	}
    29  	for _, v := range array {
    30  		src := Val{StringID, []byte(v)}
    31  
    32  		if g, err := Convert(src, GeoID); err != nil {
    33  			t.Errorf("Error parsing %s: %v", v, err)
    34  		} else {
    35  			// Marshal it back to text
    36  			got := ValueForType(StringID)
    37  			if err := Marshal(g, &got); err != nil || string(got.Value.(string)) != v {
    38  				t.Errorf("Marshal error expected %s, got %s. error %v", v, string(got.Value.(string)), err)
    39  			}
    40  
    41  			wkb := ValueForType(BinaryID)
    42  			// Marshal and unmarshal to WKB
    43  			err = Marshal(g, &wkb)
    44  			if err != nil {
    45  				t.Errorf("Error marshaling to WKB: %v", err)
    46  			}
    47  
    48  			src := Val{GeoID, []byte(wkb.Value.([]byte))}
    49  
    50  			if bg, err := Convert(src, GeoID); err != nil {
    51  				t.Errorf("Error unmarshaling WKB: %v", err)
    52  			} else if !reflect.DeepEqual(g, bg) {
    53  				t.Errorf("Expected %#v, got %#v", g, bg)
    54  			}
    55  		}
    56  	}
    57  }
    58  
    59  func TestParseGeoJsonErrors(t *testing.T) {
    60  	array := []string{
    61  		`{"type":"Curve","coordinates":[1,2]}`,
    62  		`{"type":"Feature","geometry":{"type":"Point","coordinates":[125.6,10.1]},"properties":{"name":"Dinagat Islands"}}`,
    63  		`{}`,
    64  		`thisisntjson`,
    65  	}
    66  	for _, v := range array {
    67  		src := Val{StringID, []byte(v)}
    68  		if _, err := Convert(src, GeoID); err == nil {
    69  			t.Errorf("Expected error parsing %s: %v", v, err)
    70  		}
    71  	}
    72  }