env_test.go 9.6 KB
Newer Older
martianzhang's avatar
martianzhang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * Copyright 2018 Xiaomi, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package env

import (
	"flag"
21
	"fmt"
martianzhang's avatar
martianzhang 已提交
22
	"os"
martianzhang's avatar
martianzhang 已提交
23 24
	"path/filepath"
	"runtime"
martianzhang's avatar
martianzhang 已提交
25 26 27 28
	"testing"

	"github.com/XiaoMi/soar/common"
	"github.com/XiaoMi/soar/database"
martianzhang's avatar
martianzhang 已提交
29

martianzhang's avatar
martianzhang 已提交
30
	"github.com/go-sql-driver/mysql"
martianzhang's avatar
martianzhang 已提交
31 32 33 34
	"github.com/kr/pretty"
)

var update = flag.Bool("update", false, "update .golden files")
35 36
var vEnv *VirtualEnv
var rEnv *database.Connector
martianzhang's avatar
martianzhang 已提交
37

38 39
func TestMain(m *testing.M) {
	// 初始化 init
martianzhang's avatar
martianzhang 已提交
40 41 42 43
	if common.DevPath == "" {
		_, file, _, _ := runtime.Caller(0)
		common.DevPath, _ = filepath.Abs(filepath.Dir(filepath.Join(file, ".."+string(filepath.Separator))))
	}
martianzhang's avatar
martianzhang 已提交
44 45 46
	common.BaseDir = common.DevPath
	err := common.ParseConfig("")
	common.LogIfError(err, "init ParseConfig")
martianzhang's avatar
martianzhang 已提交
47
	common.Log.Debug("env_test init")
48 49 50
	vEnv, rEnv = BuildEnv()
	if _, err = vEnv.Version(); err != nil {
		fmt.Println(err.Error(), ", By pass all advisor test cases")
martianzhang's avatar
martianzhang 已提交
51 52 53
		os.Exit(0)
	}

54 55
	if _, err := rEnv.Version(); err != nil {
		fmt.Println(err.Error(), ", By pass all advisor test cases")
martianzhang's avatar
martianzhang 已提交
56
		os.Exit(0)
martianzhang's avatar
martianzhang 已提交
57
	}
58 59 60 61 62 63 64

	// 分割线
	flag.Parse()
	m.Run()

	// 环境清理
	vEnv.CleanUp()
martianzhang's avatar
martianzhang 已提交
65 66 67
}

func TestNewVirtualEnv(t *testing.T) {
martianzhang's avatar
martianzhang 已提交
68
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
martianzhang's avatar
martianzhang 已提交
69
	testSQL := []string{
martianzhang's avatar
martianzhang 已提交
70 71
		"use sakila",
		"select frm syntaxError",
martianzhang's avatar
martianzhang 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
		"create table t(id int,c1 varchar(20),PRIMARY KEY (id));",
		"alter table t add index `idx_c1`(c1);",
		"select * from city where country_id = 44;",
		"select * from address where address2 is not null;",
		"select * from address where address2 is null;",
		"select * from address where address2 >= 44;",
		"select * from city where country_id between 44 and 107;",
		"select * from city where city like 'Ad%';",
		"select * from city where city = 'Aden' and country_id = 107;",
		"select * from city where country_id > 31 and city = 'Aden';",
		"select * from address where address_id > 8 and city_id < 400 and district = 'Nantou';",
		"select * from address where address_id > 8 and city_id < 400;",
		"select * from actor where last_update='2006-02-15 04:34:33' and last_name='CHASE' group by first_name;",
		"select * from address where last_update >='2014-09-25 22:33:47' group by district;",
		"select * from address group by address,district;",
		"select * from address where last_update='2014-09-25 22:30:27' group by district,(address_id+city_id);",
		"select * from customer where active=1 order by last_name limit 10;",
		"select * from customer order by last_name limit 10;",
		"select * from customer where address_id > 224 order by address_id limit 10;",
		"select * from customer where address_id < 224 order by address_id limit 10;",
		"select * from customer where active=1 order by last_name;",
		"select * from customer where address_id > 224 order by address_id;",
		"select * from customer where address_id in (224,510) order by last_name;",
		"select city from city where country_id = 44;",
		"select city,city_id from city where country_id = 44 and last_update='2006-02-15 04:45:25';",
		"select city from city where country_id > 44 and last_update > '2006-02-15 04:45:25';",
		"select * from city where country_id=1 and city='Kabul' order by last_update;",
		"select * from city where country_id>1 and city='Kabul' order by last_update;",
		"select * from city where city_id>251 order by last_update; ",
		"select * from city i inner join country o on i.country_id=o.country_id;",
		"select * from city i left join country o on i.city_id=o.country_id;",
		"select * from city i right join country o on i.city_id=o.country_id;",
		"select * from city i left join country o on i.city_id=o.country_id where o.country_id is null;",
		"select * from city i right join country o on i.city_id=o.country_id where i.city_id is null;",
		"select * from city i left join country o on i.city_id=o.country_id union select * from city i right join country o on i.city_id=o.country_id;",
		"select * from city i left join country o on i.city_id=o.country_id where o.country_id is null union select * from city i right join country o on i.city_id=o.country_id where i.city_id is null;",
		"select first_name,last_name,email from customer natural left join address;",
		"select first_name,last_name,email from customer natural left join address;",
		"select first_name,last_name,email from customer natural right join address;",
		"select first_name,last_name,email from customer STRAIGHT_JOIN address on customer.address_id=address.address_id;",
		"select ID,name from (select address from customer_list where SID=1 order by phone limit 50,10) a join customer_list l on (a.address=l.address) join city c on (c.city=l.city) order by phone desc;",
	}

martianzhang's avatar
martianzhang 已提交
115
	err := common.GoldenDiff(func() {
martianzhang's avatar
martianzhang 已提交
116
		for _, sql := range testSQL {
117 118
			vEnv.BuildVirtualEnv(rEnv, sql)
			switch err := vEnv.Error.(type) {
martianzhang's avatar
martianzhang 已提交
119 120 121 122 123 124
			case nil:
				pretty.Println(sql, "OK")
			case error:
				// unexpected EOF
				// 测试环境无法访问,或者被Disable的时候会进入这个分支
				pretty.Println(sql, err)
martianzhang's avatar
martianzhang 已提交
125 126
			case *mysql.MySQLError:
				if err.Number != 1061 {
martianzhang's avatar
martianzhang 已提交
127 128 129 130 131 132 133
					t.Error(err)
				}
			default:
				t.Error(err)
			}
		}
	}, t.Name(), update)
martianzhang's avatar
martianzhang 已提交
134 135 136
	if err != nil {
		t.Error(err)
	}
martianzhang's avatar
martianzhang 已提交
137
	common.Log.Debug("Exiting function: %s", common.GetFunctionName())
martianzhang's avatar
martianzhang 已提交
138 139
}

140
func TestCleanupTestDatabase(t *testing.T) {
141
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
martianzhang's avatar
martianzhang 已提交
142 143 144 145
	if common.Config.TestDSN.Disable {
		common.Log.Warn("common.Config.TestDSN.Disable=true, by pass TestCleanupTestDatabase")
		return
	}
martianzhang's avatar
martianzhang 已提交
146 147
	vEnv.Query("drop database if exists optimizer_060102150405_xxxxxxxxxxxxxxxx")
	_, err := vEnv.Query("create database optimizer_060102150405_xxxxxxxxxxxxxxxx")
148 149 150 151
	if err != nil {
		t.Error(err)
	}
	vEnv.CleanupTestDatabase()
martianzhang's avatar
martianzhang 已提交
152
	_, err = vEnv.Query("show create database optimizer_060102150405_xxxxxxxxxxxxxxxx")
153
	if err == nil {
martianzhang's avatar
martianzhang 已提交
154
		t.Error("optimizer_060102150405_xxxxxxxxxxxxxxxx exist, should be dropped")
155 156
	}

martianzhang's avatar
martianzhang 已提交
157 158
	vEnv.Query("drop database if exists optimizer_060102150405")
	_, err = vEnv.Query("create database optimizer_060102150405")
159 160 161 162
	if err != nil {
		t.Error(err)
	}
	vEnv.CleanupTestDatabase()
martianzhang's avatar
martianzhang 已提交
163
	_, err = vEnv.Query("drop database optimizer_060102150405")
164
	if err != nil {
martianzhang's avatar
martianzhang 已提交
165
		t.Error("optimizer_060102150405 not exist, should not be dropped")
166
	}
martianzhang's avatar
martianzhang 已提交
167
	common.Log.Debug("Exiting function: %s", common.GetFunctionName())
168 169
}

martianzhang's avatar
martianzhang 已提交
170
func TestGenTableColumns(t *testing.T) {
171
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
martianzhang's avatar
martianzhang 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

	pretty.Println(common.Config.TestDSN.Disable)
	if common.Config.TestDSN.Disable {
		common.Log.Warn("common.Config.TestDSN.Disable=true, by pass TestGenTableColumns")
		return
	}

	// 只能对sakila数据库进行测试
	if rEnv.Database == "sakila" {
		testSQL := []string{
			"select * from city where country_id = 44;",
			"select country_id from city where country_id = 44;",
			"select country_id from city where country_id > 44;",
		}

		metaList := []common.Meta{
			{
				"": &common.DB{
					Table: map[string]*common.Table{
						"city": common.NewTable("city"),
					},
				},
			},
			{
				"sakila": &common.DB{
					Table: map[string]*common.Table{
						"city": common.NewTable("city"),
					},
				},
			},
			{
				"sakila": &common.DB{
					Table: map[string]*common.Table{
						"city": {
							TableName: "city",
							Column: map[string]*common.Column{
								"country_id": {
									Name: "country_id",
								},
							},
						},
					},
				},
			},
		}

		for i, sql := range testSQL {
			vEnv.BuildVirtualEnv(rEnv, sql)
			tFlag := false
			columns := vEnv.GenTableColumns(metaList[i])
			if _, ok := columns["sakila"]; ok {
				if _, okk := columns["sakila"]["city"]; okk {
					if length := len(columns["sakila"]["city"]); length >= 1 {
						tFlag = true
					}
				}
			}

			if !tFlag {
				t.Errorf("columns: \n%s", pretty.Sprint(columns))
			}
		}
	}
martianzhang's avatar
martianzhang 已提交
235 236 237 238
	common.Log.Debug("Exiting function: %s", common.GetFunctionName())
}

func TestCreateTable(t *testing.T) {
239
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
martianzhang's avatar
martianzhang 已提交
240 241 242
	orgSamplingCondition := common.Config.SamplingCondition
	common.Config.SamplingCondition = "LIMIT 1"

243 244
	orgREnvDatabase := rEnv.Database
	rEnv.Database = "sakila"
martianzhang's avatar
martianzhang 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
	tables := []string{
		"actor",
		"address",
		"category",
		"city",
		"country",
		"customer",
		"film",
		"film_actor",
		"film_category",
		"film_text",
		"inventory",
		"language",
		"payment",
		"rental",
		"staff",
		"store",
martianzhang's avatar
martianzhang 已提交
262 263 264 265 266 267 268
		"staff_list",
		"customer_list",
		"actor_info",
		"sales_by_film_category",
		"sales_by_store",
		"nicer_but_slower_film_list",
		"film_list",
martianzhang's avatar
martianzhang 已提交
269 270
	}
	for _, table := range tables {
271
		err := vEnv.createTable(rEnv, table)
martianzhang's avatar
martianzhang 已提交
272 273 274 275 276
		if err != nil {
			t.Error(err)
		}
	}
	common.Config.SamplingCondition = orgSamplingCondition
277
	rEnv.Database = orgREnvDatabase
martianzhang's avatar
martianzhang 已提交
278 279 280 281
	common.Log.Debug("Exiting function: %s", common.GetFunctionName())
}

func TestCreateDatabase(t *testing.T) {
282 283 284 285
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
	orgREnvDatabase := rEnv.Database
	rEnv.Database = "sakila"
	err := vEnv.createDatabase(rEnv)
martianzhang's avatar
martianzhang 已提交
286 287 288 289 290 291 292 293 294 295
	if err != nil {
		t.Error(err)
	}
	if vEnv.DBHash("sakila") == "sakila" {
		t.Errorf("database: sakila rehashed failed!")
	}

	if vEnv.DBHash("not_exist_db") != "not_exist_db" {
		t.Errorf("database: not_exist_db rehashed!")
	}
296
	rEnv.Database = orgREnvDatabase
martianzhang's avatar
martianzhang 已提交
297
	common.Log.Debug("Exiting function: %s", common.GetFunctionName())
martianzhang's avatar
martianzhang 已提交
298
}