1// Copyright 2015 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 bigquery
16
17import (
18	"errors"
19	"strings"
20	"testing"
21
22	"cloud.google.com/go/internal/testutil"
23	bq "google.golang.org/api/bigquery/v2"
24)
25
26func rowInsertionError(msg string) RowInsertionError {
27	return RowInsertionError{Errors: []error{errors.New(msg)}}
28}
29
30func TestPutMultiErrorString(t *testing.T) {
31	testCases := []struct {
32		errs PutMultiError
33		want string
34	}{
35		{
36			errs: PutMultiError{},
37			want: "0 row insertions failed",
38		},
39		{
40			errs: PutMultiError{rowInsertionError("a")},
41			want: "1 row insertion failed",
42		},
43		{
44			errs: PutMultiError{rowInsertionError("a"), rowInsertionError("b")},
45			want: "2 row insertions failed",
46		},
47	}
48
49	for _, tc := range testCases {
50		if tc.errs.Error() != tc.want {
51			t.Errorf("PutMultiError string: got:\n%v\nwant:\n%v", tc.errs.Error(), tc.want)
52		}
53	}
54}
55
56func TestMultiErrorString(t *testing.T) {
57	testCases := []struct {
58		errs MultiError
59		want string
60	}{
61		{
62			errs: MultiError{},
63			want: "(0 errors)",
64		},
65		{
66			errs: MultiError{errors.New("a")},
67			want: "a",
68		},
69		{
70			errs: MultiError{errors.New("a"), errors.New("b")},
71			want: "a (and 1 other error)",
72		},
73		{
74			errs: MultiError{errors.New("a"), errors.New("b"), errors.New("c")},
75			want: "a (and 2 other errors)",
76		},
77	}
78
79	for _, tc := range testCases {
80		if tc.errs.Error() != tc.want {
81			t.Errorf("PutMultiError string: got:\n%v\nwant:\n%v", tc.errs.Error(), tc.want)
82		}
83	}
84}
85
86func TestErrorFromErrorProto(t *testing.T) {
87	for _, test := range []struct {
88		in   *bq.ErrorProto
89		want *Error
90	}{
91		{nil, nil},
92		{
93			in:   &bq.ErrorProto{Location: "L", Message: "M", Reason: "R"},
94			want: &Error{Location: "L", Message: "M", Reason: "R"},
95		},
96	} {
97		if got := bqToError(test.in); !testutil.Equal(got, test.want) {
98			t.Errorf("%v: got %v, want %v", test.in, got, test.want)
99		}
100	}
101}
102
103func TestErrorString(t *testing.T) {
104	e := &Error{Location: "<L>", Message: "<M>", Reason: "<R>"}
105	got := e.Error()
106	if !strings.Contains(got, "<L>") || !strings.Contains(got, "<M>") || !strings.Contains(got, "<R>") {
107		t.Errorf(`got %q, expected to see "<L>", "<M>" and "<R>"`, got)
108	}
109}
110