1// Copyright 2017 Google LLC
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
15package datastore
16
17import (
18	"context"
19	"testing"
20
21	"github.com/golang/protobuf/proto"
22	pb "google.golang.org/genproto/googleapis/datastore/v1"
23)
24
25func TestNewTransaction(t *testing.T) {
26	var got *pb.BeginTransactionRequest
27	client := &Client{
28		dataset: "project",
29		client: &fakeDatastoreClient{
30			beginTransaction: func(req *pb.BeginTransactionRequest) (*pb.BeginTransactionResponse, error) {
31				got = req
32				return &pb.BeginTransactionResponse{
33					Transaction: []byte("tid"),
34				}, nil
35			},
36		},
37	}
38	ctx := context.Background()
39	for _, test := range []struct {
40		settings *transactionSettings
41		want     *pb.BeginTransactionRequest
42	}{
43		{
44			&transactionSettings{},
45			&pb.BeginTransactionRequest{ProjectId: "project"},
46		},
47		{
48			&transactionSettings{readOnly: true},
49			&pb.BeginTransactionRequest{
50				ProjectId: "project",
51				TransactionOptions: &pb.TransactionOptions{
52					Mode: &pb.TransactionOptions_ReadOnly_{ReadOnly: &pb.TransactionOptions_ReadOnly{}},
53				},
54			},
55		},
56		{
57			&transactionSettings{prevID: []byte("tid")},
58			&pb.BeginTransactionRequest{
59				ProjectId: "project",
60				TransactionOptions: &pb.TransactionOptions{
61					Mode: &pb.TransactionOptions_ReadWrite_{ReadWrite: &pb.TransactionOptions_ReadWrite{
62						PreviousTransaction: []byte("tid"),
63					},
64					},
65				},
66			},
67		},
68	} {
69		_, err := client.newTransaction(ctx, test.settings)
70		if err != nil {
71			t.Fatal(err)
72		}
73		if !proto.Equal(got, test.want) {
74			t.Errorf("%+v:\ngot  %+v\nwant %+v", test.settings, got, test.want)
75		}
76	}
77}
78