...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/store/event/event_test.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/store/event

     1  // Copyright 2020 Chaos Mesh Authors.
     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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package event
    15  
    16  import (
    17  	"context"
    18  	"database/sql"
    19  	"reflect"
    20  	"regexp"
    21  	"strings"
    22  	"testing"
    23  	"time"
    24  
    25  	"github.com/chaos-mesh/chaos-mesh/pkg/core"
    26  	"github.com/chaos-mesh/chaos-mesh/pkg/store/dbstore"
    27  
    28  	sqlmock "github.com/DATA-DOG/go-sqlmock"
    29  	"github.com/jinzhu/gorm"
    30  	. "github.com/onsi/ginkgo"
    31  	. "github.com/onsi/gomega"
    32  )
    33  
    34  func TestEvent(t *testing.T) {
    35  	RegisterFailHandler(Fail)
    36  	RunSpecs(t, "Event Suite")
    37  }
    38  
    39  var _ = Describe("event", func() {
    40  	var (
    41  		es      *eventStore
    42  		mock    sqlmock.Sqlmock
    43  		event0  *core.Event
    44  		event1  *core.Event
    45  		timeNow time.Time
    46  	)
    47  
    48  	BeforeEach(func() {
    49  		var db *sql.DB
    50  		var err error
    51  		db, mock, err = sqlmock.New()
    52  		Expect(err).ShouldNot(HaveOccurred())
    53  
    54  		gdb, err := gorm.Open("sqlite3", db)
    55  		Expect(err).ShouldNot(HaveOccurred())
    56  
    57  		es = &eventStore{db: &dbstore.DB{DB: gdb}}
    58  
    59  		timeNow = time.Now()
    60  
    61  		event0 = &core.Event{
    62  			ID:        0,
    63  			CreatedAt: timeNow,
    64  			Kind:      "testKind",
    65  			Type:      "testType",
    66  			Reason:    "testReason",
    67  			Message:   "testMessage",
    68  			Name:      "testName",
    69  			Namespace: "testNamespace",
    70  			ObjectID:  "testID0",
    71  		}
    72  		event1 = &core.Event{
    73  			ID:        1,
    74  			CreatedAt: timeNow,
    75  			Kind:      "testKind",
    76  			Type:      "testType",
    77  			Reason:    "testReason",
    78  			Message:   "testMessage",
    79  			Name:      "testName",
    80  			Namespace: "testNamespace",
    81  			ObjectID:  "testID1",
    82  		}
    83  	})
    84  
    85  	AfterEach(func() {
    86  		err := mock.ExpectationsWereMet()
    87  		Expect(err).ShouldNot(HaveOccurred())
    88  	})
    89  
    90  	Context("min", func() {
    91  		It("x", func() {
    92  			x := 1
    93  			y := 2
    94  			res := min(x, y)
    95  			Expect(res).Should(Equal(x))
    96  		})
    97  
    98  		It("y", func() {
    99  			x := 2
   100  			y := 1
   101  			res := min(x, y)
   102  			Expect(res).Should(Equal(y))
   103  		})
   104  	})
   105  
   106  	Context("list", func() {
   107  		It("found", func() {
   108  			rows := sqlmock.
   109  				NewRows([]string{"id", "created_at", "kind", "type", "reason", "message", "name",
   110  					"namespace", "object_id"}).
   111  				AddRow(event0.ID, event0.CreatedAt, event0.Kind, event0.Type, event0.Reason,
   112  					event0.Message, event0.Name, event0.Namespace, event0.ObjectID)
   113  
   114  			sqlSelect := `SELECT * FROM "events"`
   115  			mock.ExpectQuery(regexp.QuoteMeta(sqlSelect)).WillReturnRows(rows)
   116  
   117  			events, err := es.List(context.TODO())
   118  			Expect(err).ShouldNot(HaveOccurred())
   119  			Expect(events[0]).Should(Equal(event0))
   120  		})
   121  
   122  		It("not found", func() {
   123  			mock.ExpectQuery(`.+`).WillReturnRows(sqlmock.NewRows(nil))
   124  			events, err := es.List(context.TODO())
   125  			Expect(err).ShouldNot(HaveOccurred())
   126  			Expect(len(events)).Should(Equal(0))
   127  		})
   128  	})
   129  
   130  	Context("listByUID", func() {
   131  		It("found", func() {
   132  			mockedRow := []*sqlmock.Rows{
   133  				sqlmock.NewRows([]string{"id", "created_at", "kind", "type", "reason", "message", "name",
   134  					"namespace", "object_id"}).
   135  					AddRow(event0.ID, event0.CreatedAt, event0.Kind, event0.Type, event0.Reason,
   136  						event0.Message, event0.Name, event0.Namespace, event0.ObjectID),
   137  				sqlmock.NewRows([]string{"id", "created_at", "kind", "type", "reason", "message", "name",
   138  					"namespace", "object_id"}).
   139  					AddRow(event1.ID, event1.CreatedAt, event1.Kind, event1.Type, event1.Reason,
   140  						event1.Message, event1.Name, event1.Namespace, event1.ObjectID),
   141  			}
   142  
   143  			sqlSelect := `SELECT * FROM "events" WHERE (object_id = ?)`
   144  			mock.ExpectQuery(regexp.QuoteMeta(sqlSelect)).WithArgs(event0.ObjectID).WillReturnRows(mockedRow[0])
   145  
   146  			events, err := es.ListByUID(context.TODO(), event0.ObjectID)
   147  			Expect(err).ShouldNot(HaveOccurred())
   148  			Expect(events[0]).Should(Equal(event0))
   149  		})
   150  
   151  		It("not found", func() {
   152  			mock.ExpectQuery(`.+`).WillReturnRows(sqlmock.NewRows(nil))
   153  			events, err := es.ListByUID(context.TODO(), "testIDNotFound")
   154  			Expect(err).ShouldNot(HaveOccurred())
   155  			Expect(len(events)).Should(Equal(0))
   156  		})
   157  	})
   158  
   159  	Context("listByExperiment", func() {
   160  		It("found", func() {
   161  			mockedRow := []*sqlmock.Rows{
   162  				sqlmock.NewRows([]string{"id", "created_at", "kind", "type", "reason", "message", "name",
   163  					"namespace", "object_id"}).
   164  					AddRow(event0.ID, event0.CreatedAt, event0.Kind, event0.Type, event0.Reason,
   165  						event0.Message, event0.Name, event0.Namespace, event0.ObjectID),
   166  				sqlmock.NewRows([]string{"id", "created_at", "kind", "type", "reason", "message", "name",
   167  					"namespace", "object_id"}).
   168  					AddRow(event1.ID, event1.CreatedAt, event1.Kind, event1.Type, event1.Reason,
   169  						event1.Message, event1.Name, event1.Namespace, event1.ObjectID),
   170  			}
   171  
   172  			sqlSelect := `SELECT * FROM "events" WHERE (namespace = ? and name = ? and kind = ?)`
   173  			mock.ExpectQuery(regexp.QuoteMeta(sqlSelect)).WithArgs(event0.Namespace, event0.Name, event0.Kind).WillReturnRows(mockedRow[0])
   174  
   175  			events, err := es.ListByExperiment(context.TODO(), event0.Namespace, event0.Name, event0.Kind)
   176  			Expect(err).ShouldNot(HaveOccurred())
   177  			Expect(events[0]).Should(Equal(event0))
   178  		})
   179  
   180  		It("not found", func() {
   181  			mock.ExpectQuery(`.+`).WillReturnRows(sqlmock.NewRows(nil))
   182  			events, err := es.ListByExperiment(context.TODO(), "testNamespaceNotFound", "testNameNotFound", "testKindNotFound")
   183  			Expect(err).ShouldNot(HaveOccurred())
   184  			Expect(len(events)).Should(Equal(0))
   185  		})
   186  	})
   187  
   188  	Context("find", func() {
   189  		It("found", func() {
   190  			mockedRow := []*sqlmock.Rows{
   191  				sqlmock.NewRows([]string{"id", "created_at", "kind", "type", "reason", "message", "name",
   192  					"namespace", "object_id"}).
   193  					AddRow(event0.ID, event0.CreatedAt, event0.Kind, event0.Type, event0.Reason,
   194  						event0.Message, event0.Name, event0.Namespace, event0.ObjectID),
   195  				sqlmock.NewRows([]string{"id", "created_at", "kind", "type", "reason", "message", "name",
   196  					"namespace", "object_id"}).
   197  					AddRow(event1.ID, event1.CreatedAt, event1.Kind, event1.Type, event1.Reason,
   198  						event1.Message, event1.Name, event1.Namespace, event1.ObjectID),
   199  			}
   200  
   201  			sqlSelect := `SELECT * FROM "events" WHERE (id = ?)`
   202  			mock.ExpectQuery(regexp.QuoteMeta(sqlSelect)).WithArgs(event0.ID).WillReturnRows(mockedRow[0])
   203  
   204  			event, err := es.Find(context.TODO(), event0.ID)
   205  			Expect(err).ShouldNot(HaveOccurred())
   206  			Expect(event).Should(Equal(event0))
   207  		})
   208  
   209  		It("not found", func() {
   210  			mock.ExpectQuery(`.+`).WillReturnRows(sqlmock.NewRows(nil))
   211  			_, err := es.Find(context.TODO(), 30)
   212  			Expect(err).Should(HaveOccurred())
   213  		})
   214  	})
   215  
   216  	Context("listByFilter", func() {
   217  		It("limitStr wrong", func() {
   218  			filter := core.Filter{
   219  				LimitStr: "testWrong",
   220  			}
   221  			_, err := es.ListByFilter(context.TODO(), filter)
   222  			Expect(err).Should(HaveOccurred())
   223  			Expect(strings.Contains(err.Error(), "the format of the limitStr is wrong")).To(Equal(true))
   224  		})
   225  
   226  		It("startTimeStr wrong", func() {
   227  			filter := core.Filter{
   228  				CreateTimeStr: "testWrong",
   229  			}
   230  			_, err := es.ListByFilter(context.TODO(), filter)
   231  			Expect(err).Should(HaveOccurred())
   232  			Expect(strings.Contains(err.Error(), "the format of the createTime is wrong")).To(Equal(true))
   233  		})
   234  
   235  		It("empty args", func() {
   236  			rows := sqlmock.
   237  				NewRows([]string{"id", "created_at", "kind", "type", "reason", "message", "name",
   238  					"namespace", "object_id"}).
   239  				AddRow(event0.ID, event0.CreatedAt, event0.Kind, event0.Type, event0.Reason,
   240  					event0.Message, event0.Name, event0.Namespace, event0.ObjectID)
   241  			sqlSelect := `SELECT * FROM "events"`
   242  			mock.ExpectQuery(regexp.QuoteMeta(sqlSelect)).WillReturnRows(rows)
   243  
   244  			filter := core.Filter{}
   245  			events, err := es.ListByFilter(context.TODO(), filter)
   246  			Expect(err).ShouldNot(HaveOccurred())
   247  			Expect(events[0]).Should(Equal(event0))
   248  		})
   249  	})
   250  })
   251  
   252  func TestConstructQueryArgs(t *testing.T) {
   253  	cases := []struct {
   254  		kind          string
   255  		ns            string
   256  		name          string
   257  		uid           string
   258  		createTime    string
   259  		expectedQuery string
   260  		expectedArgs  []string
   261  	}{
   262  		{
   263  			name:          "",
   264  			ns:            "",
   265  			uid:           "",
   266  			kind:          "",
   267  			createTime:    "",
   268  			expectedQuery: "",
   269  			expectedArgs:  []string{},
   270  		},
   271  		{
   272  			name:          "testName",
   273  			ns:            "",
   274  			uid:           "",
   275  			kind:          "",
   276  			createTime:    "",
   277  			expectedQuery: "name = ?",
   278  			expectedArgs:  []string{"testName"},
   279  		},
   280  		{
   281  			name:          "",
   282  			ns:            "testNamespace",
   283  			uid:           "",
   284  			kind:          "",
   285  			createTime:    "",
   286  			expectedQuery: "namespace = ?",
   287  			expectedArgs:  []string{"testNamespace"},
   288  		},
   289  		{
   290  			name:          "",
   291  			ns:            "",
   292  			uid:           "testUID",
   293  			kind:          "",
   294  			createTime:    "",
   295  			expectedQuery: "object_id = ?",
   296  			expectedArgs:  []string{"testUID"},
   297  		},
   298  		{
   299  			name:          "",
   300  			ns:            "",
   301  			uid:           "",
   302  			kind:          "testKind",
   303  			createTime:    "",
   304  			expectedQuery: "kind = ?",
   305  			expectedArgs:  []string{"testKind"},
   306  		},
   307  		{
   308  			name:          "",
   309  			ns:            "",
   310  			uid:           "",
   311  			kind:          "",
   312  			createTime:    "20200101",
   313  			expectedQuery: "created_at >= ?",
   314  			expectedArgs:  []string{"20200101"},
   315  		},
   316  		{
   317  			name:          "testName",
   318  			ns:            "testNamespace",
   319  			uid:           "",
   320  			kind:          "",
   321  			createTime:    "",
   322  			expectedQuery: "name = ? AND namespace = ?",
   323  			expectedArgs:  []string{"testName", "testNamespace"},
   324  		},
   325  		{
   326  			name:          "testName",
   327  			ns:            "testNamespace",
   328  			uid:           "testUID",
   329  			kind:          "",
   330  			createTime:    "",
   331  			expectedQuery: "name = ? AND namespace = ? AND object_id = ?",
   332  			expectedArgs:  []string{"testName", "testNamespace", "testUID"},
   333  		},
   334  		{
   335  			name:          "testName",
   336  			ns:            "testNamespace",
   337  			uid:           "testUID",
   338  			kind:          "testKind",
   339  			createTime:    "",
   340  			expectedQuery: "name = ? AND namespace = ? AND object_id = ? AND kind = ?",
   341  			expectedArgs:  []string{"testName", "testNamespace", "testUID", "testKind"},
   342  		},
   343  		{
   344  			name:          "testName",
   345  			ns:            "testNamespace",
   346  			uid:           "testUID",
   347  			kind:          "testKind",
   348  			createTime:    "20200101",
   349  			expectedQuery: "name = ? AND namespace = ? AND object_id = ? AND kind = ? AND created_at >= ?",
   350  			expectedArgs:  []string{"testName", "testNamespace", "testUID", "testKind", "20200101"},
   351  		},
   352  		{
   353  			name:          "testName",
   354  			ns:            "testNamespace",
   355  			uid:           "testUID",
   356  			kind:          "testKind",
   357  			createTime:    "20200101",
   358  			expectedQuery: "name = ? AND namespace = ? AND object_id = ? AND kind = ? AND created_at >= ?",
   359  			expectedArgs:  []string{"testName", "testNamespace", "testUID", "testKind", "20200101"},
   360  		},
   361  	}
   362  
   363  	for _, c := range cases {
   364  		query, args := constructQueryArgs(c.name, c.ns, c.uid, c.kind, c.createTime)
   365  		argString := []string{}
   366  		for _, arg := range args {
   367  			argString = append(argString, arg.(string))
   368  		}
   369  		if query != c.expectedQuery {
   370  			t.Errorf("expected query %s but got %s", c.expectedQuery, query)
   371  		}
   372  		if !reflect.DeepEqual(c.expectedArgs, argString) {
   373  			t.Errorf("expected args %v but got %v", c.expectedArgs, argString)
   374  		}
   375  	}
   376  }
   377