1// Copyright 2019 Google Inc. All Rights Reserved.
2// Use of this source code is governed by the Apache 2.0
3// license that can be found in the LICENSE file.
4
5package datastore
6
7import (
8	"reflect"
9	"testing"
10)
11
12func TestKeyConversion(t *testing.T) {
13	var tests = []struct {
14		desc       string
15		key        *Key
16		encodedKey string
17	}{
18		{
19			desc: "A control test for legacy to legacy key conversion int as the key",
20			key: &Key{
21				kind:  "Person",
22				intID: 1,
23				appID: "glibrary",
24			},
25			encodedKey: "aghnbGlicmFyeXIMCxIGUGVyc29uGAEM",
26		},
27		{
28			desc: "A control test for legacy to legacy key conversion string as the key",
29			key: &Key{
30				kind:     "Graph",
31				stringID: "graph:7-day-active",
32				appID:    "glibrary",
33			},
34			encodedKey: "aghnbGlicmFyeXIdCxIFR3JhcGgiEmdyYXBoOjctZGF5LWFjdGl2ZQw",
35		},
36
37		// These are keys encoded with cloud.google.com/go/datastore
38		// Standard int as the key
39		{
40			desc: "Convert new key format to old key with int id",
41			key: &Key{
42				kind:  "WordIndex",
43				intID: 1033,
44				appID: "glibrary",
45			},
46			encodedKey: "Eg4KCVdvcmRJbmRleBCJCA",
47		},
48		// These are keys encoded with cloud.google.com/go/datastore
49		// Standard string
50		{
51			desc: "Convert new key format to old key with string id",
52			key: &Key{
53				kind:     "WordIndex",
54				stringID: "IAmAnID",
55				appID:    "glibrary",
56			},
57			encodedKey: "EhQKCVdvcmRJbmRleBoHSUFtQW5JRA",
58		},
59
60		// These are keys encoded with cloud.google.com/go/datastore
61		// ID String with parent as string
62		{
63			desc: "Convert new key format to old key with string id with a parent",
64			key: &Key{
65				kind:     "WordIndex",
66				stringID: "IAmAnID",
67				appID:    "glibrary",
68				parent: &Key{
69					kind:     "LetterIndex",
70					stringID: "IAmAnotherID",
71					appID:    "glibrary",
72				},
73			},
74			encodedKey: "EhsKC0xldHRlckluZGV4GgxJQW1Bbm90aGVySUQSFAoJV29yZEluZGV4GgdJQW1BbklE",
75		},
76	}
77
78	// Simulate the key converter enablement
79	keyConversion.appID = "glibrary"
80	for _, tc := range tests {
81		dk, err := DecodeKey(tc.encodedKey)
82		if err != nil {
83			t.Fatalf("DecodeKey: %v", err)
84		}
85		if !reflect.DeepEqual(dk, tc.key) {
86			t.Errorf("%s: got %+v, want %+v", tc.desc, dk, tc.key)
87		}
88	}
89}
90