File: mysql_test.go

package info (click to toggle)
wait4x 3.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 740 kB
  • sloc: makefile: 248; sh: 13
file content (348 lines) | stat: -rw-r--r-- 11,857 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright 2019-2025 The Wait4X Authors
//
// 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 cmd provides the command-line interface for the Wait4X application.
package cmd

import (
	"context"
	"testing"

	"github.com/spf13/cobra"
	"github.com/stretchr/testify/suite"
	"github.com/testcontainers/testcontainers-go"
	"github.com/testcontainers/testcontainers-go/log"
	"github.com/testcontainers/testcontainers-go/modules/mysql"
	"wait4x.dev/v3/internal/test"
)

// MySQLCommandSuite is a test suite for MySQL command functionality
type MySQLCommandSuite struct {
	suite.Suite

	// Shared resources for the test suite
	rootCmd          *cobra.Command
	mysqlCmd         *cobra.Command
	container        *mysql.MySQLContainer
	connectionString string
}

// SetupSuite sets up test suite resources
func (s *MySQLCommandSuite) SetupSuite() {
	// Set up a MySQL container for tests that need an active connection
	var err error
	s.container, err = mysql.Run(
		context.Background(),
		"mysql:8.0.36",
		testcontainers.WithLogger(log.TestLogger(s.T())),
	)
	s.Require().NoError(err)

	// Get the connection string for testing
	s.connectionString, err = s.container.ConnectionString(context.Background())
	s.Require().NoError(err)
}

// TearDownSuite tears down test suite resources
func (s *MySQLCommandSuite) TearDownSuite() {
	// Close container
	if s.container != nil {
		err := s.container.Terminate(context.Background())
		s.Require().NoError(err)
	}
}

// SetupTest sets up each test
func (s *MySQLCommandSuite) SetupTest() {
	s.rootCmd = NewRootCommand()
	s.mysqlCmd = NewMysqlCommand()
	s.rootCmd.AddCommand(s.mysqlCmd)
}

// TestNewMysqlCommand tests the MySQL command creation
func (s *MySQLCommandSuite) TestNewMysqlCommand() {
	cmd := NewMysqlCommand()

	s.Equal("mysql DSN... [flags] [-- command [args...]]", cmd.Use)
	s.Equal("Check MySQL connection", cmd.Short)
	s.NotNil(cmd.Example)
	s.Contains(cmd.Example, "wait4x mysql user:password@tcp(localhost:5555)/dbname?tls=skip-verify")
	s.Contains(cmd.Example, "wait4x mysql username:password@unix(/tmp/mysql.sock)/myDatabase")
}

// TestMysqlCommandValidation tests argument validation
func (s *MySQLCommandSuite) TestMysqlCommandValidation() {
	// Test missing arguments
	_, err := test.ExecuteCommand(s.rootCmd, "mysql")
	s.Require().Error(err)
	s.Equal("DSN is required argument for the mysql command", err.Error())

	// Test empty arguments
	err = s.mysqlCmd.Args(s.mysqlCmd, []string{})
	s.Require().Error(err)
	s.Equal("DSN is required argument for the mysql command", err.Error())

	// Test valid arguments
	err = s.mysqlCmd.Args(s.mysqlCmd, []string{"user:password@tcp(localhost:3306)/dbname"})
	s.NoError(err)

	err = s.mysqlCmd.Args(s.mysqlCmd, []string{
		"user:password@tcp(localhost:3306)/dbname",
		"user2:password2@tcp(localhost:3307)/dbname2",
	})
	s.NoError(err)
}

// TestMysqlConnectionScenarios tests various connection scenarios
func (s *MySQLCommandSuite) TestMysqlConnectionScenarios() {
	// Test successful connection
	_, err := test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString)
	s.NoError(err)

	// Test connection failure (timeout)
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", "user:password@tcp(localhost:8080)/dbname", "-t", "2s")
	s.Error(err)
	s.Equal(context.DeadlineExceeded, err)

	// Test connection timeout with black-hole IP
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", "user:password@tcp(240.0.0.1:3306)/dbname", "-t", "1s")
	s.Error(err)
	s.Equal(context.DeadlineExceeded, err)

	// Test multiple DSNs (mixed valid/invalid)
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString, "user:password@tcp(localhost:8080)/dbname", "-t", "2s")
	s.Error(err)
	s.Equal(context.DeadlineExceeded, err)
}

// TestMysqlCommandFlags tests all command flags
func (s *MySQLCommandSuite) TestMysqlCommandFlags() {
	// Test interval flag
	_, err := test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString, "-i", "500ms")
	s.NoError(err)

	// Test timeout flag
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString, "-t", "0")
	s.NoError(err)

	// Test quiet mode
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString, "-q")
	s.NoError(err)

	// Test no color flag
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString, "--no-color")
	s.NoError(err)

	// Test dash separator for command execution
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString, "--", "echo", "success")
	s.NoError(err)
}

// TestMysqlCommandInvertCheck tests invert check functionality
func (s *MySQLCommandSuite) TestMysqlCommandInvertCheck() {
	// With invert check, a successful connection should fail
	_, err := test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString, "-v", "-t", "2s")
	s.Error(err)
	s.Equal(context.DeadlineExceeded, err)

	// With invert check, a failed connection should succeed
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", "user:password@tcp(localhost:8080)/dbname", "-v", "-t", "2s")
	s.NoError(err)
}

// TestMysqlCommandBackoffPolicy tests backoff policy functionality
func (s *MySQLCommandSuite) TestMysqlCommandBackoffPolicy() {
	// Test exponential backoff
	_, err := test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString, "--backoff-policy", "exponential")
	s.NoError(err)

	// Test invalid backoff policy
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString, "--backoff-policy", "invalid")
	s.Error(err)
	s.Contains(err.Error(), "--backoff-policy must be one of")

	// Test backoff coefficient
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString, "--backoff-policy", "exponential", "--backoff-exponential-coefficient", "1.5")
	s.NoError(err)

	// Test backoff max interval
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString, "--backoff-policy", "exponential", "--backoff-exponential-max-interval", "3s")
	s.NoError(err)

	// Test invalid backoff max interval
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", s.connectionString, "--backoff-policy", "exponential", "--backoff-exponential-max-interval", "100ms", "-i", "200ms")
	s.Require().Error(err)
	s.Contains(err.Error(), "--backoff-exponential-max-interval must be greater than --interval")
}

// TestMysqlCommandDSNFormats tests various DSN formats
func (s *MySQLCommandSuite) TestMysqlCommandDSNFormats() {
	// Test invalid DSN format
	_, err := test.ExecuteCommand(s.rootCmd, "mysql", "invalid-dsn-format", "-t", "2s")
	s.Require().Error(err)
	s.Contains(err.Error(), "can't retrieve the checker identity")

	// Test Unix socket DSN (will timeout)
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", "user:password@unix(/tmp/mysql.sock)/dbname", "-t", "2s")
	s.Error(err)
	s.Equal(context.DeadlineExceeded, err)

	// Test TLS DSN (will timeout)
	_, err = test.ExecuteCommand(s.rootCmd, "mysql", "user:password@tcp(240.0.0.1:3306)/dbname?tls=skip-verify", "-t", "1s")
	s.Error(err)
	s.Equal(context.DeadlineExceeded, err)
}

// TestMysqlCommandTableDriven tests the MySQL command with various scenarios using table-driven tests
func (s *MySQLCommandSuite) TestMysqlCommandTableDriven() {
	tests := []struct {
		name         string
		args         []string
		shouldError  bool
		errorType    string
		errorMessage string
	}{
		{
			name:        "valid connection",
			args:        []string{"mysql", s.connectionString},
			shouldError: false,
		},
		{
			name:         "invalid DSN format",
			args:         []string{"mysql", "invalid-dsn"},
			shouldError:  true,
			errorType:    "validation",
			errorMessage: "can't retrieve the checker identity",
		},
		{
			name:         "connection timeout",
			args:         []string{"mysql", "user:password@tcp(240.0.0.1:3306)/dbname", "-t", "1s"},
			shouldError:  true,
			errorType:    "timeout",
			errorMessage: "",
		},
		{
			name:         "missing DSN argument",
			args:         []string{"mysql"},
			shouldError:  true,
			errorType:    "validation",
			errorMessage: "DSN is required argument for the mysql command",
		},
		{
			name:        "multiple valid DSNs",
			args:        []string{"mysql", s.connectionString, s.connectionString},
			shouldError: false,
		},
		{
			name:         "mixed valid and invalid DSNs",
			args:         []string{"mysql", s.connectionString, "user:password@tcp(localhost:8080)/dbname", "-t", "2s"},
			shouldError:  true,
			errorType:    "timeout",
			errorMessage: "",
		},
		{
			name:        "with custom interval",
			args:        []string{"mysql", s.connectionString, "-i", "500ms"},
			shouldError: false,
		},
		{
			name:        "with exponential backoff",
			args:        []string{"mysql", s.connectionString, "--backoff-policy", "exponential"},
			shouldError: false,
		},
		{
			name:         "with invalid backoff policy",
			args:         []string{"mysql", s.connectionString, "--backoff-policy", "invalid"},
			shouldError:  true,
			errorType:    "validation",
			errorMessage: "--backoff-policy must be one of",
		},
		{
			name:         "with invert check on valid connection",
			args:         []string{"mysql", s.connectionString, "-v", "-t", "2s"},
			shouldError:  true,
			errorType:    "timeout",
			errorMessage: "",
		},
		{
			name:        "with invert check on invalid connection",
			args:        []string{"mysql", "user:password@tcp(localhost:8080)/dbname", "-v", "-t", "2s"},
			shouldError: false,
		},
		{
			name:        "with quiet mode",
			args:        []string{"mysql", s.connectionString, "-q"},
			shouldError: false,
		},
		{
			name:        "with no color",
			args:        []string{"mysql", s.connectionString, "--no-color"},
			shouldError: false,
		},
		{
			name:        "with zero timeout",
			args:        []string{"mysql", s.connectionString, "-t", "0"},
			shouldError: false,
		},
		{
			name:        "with command execution",
			args:        []string{"mysql", s.connectionString, "--", "echo", "success"},
			shouldError: false,
		},
	}

	for _, tt := range tests {
		s.Run(tt.name, func() {
			// Create a fresh root command for each test to avoid flag pollution
			rootCmd := NewRootCommand()
			mysqlCmd := NewMysqlCommand()
			rootCmd.AddCommand(mysqlCmd)

			_, err := test.ExecuteCommand(rootCmd, tt.args...)

			if tt.shouldError {
				s.Require().Error(err)
				if tt.errorType == "timeout" {
					s.Require().ErrorIs(err, context.DeadlineExceeded)
				} else if tt.errorType == "validation" {
					s.Require().ErrorContains(err, tt.errorMessage)
				} else if tt.errorType == "connection" {
					s.Require().ErrorContains(err, tt.errorMessage)
				}
			} else {
				s.Require().NoError(err)
			}
		})
	}
}

// TestMysqlCommandHelp tests the MySQL command help
func (s *MySQLCommandSuite) TestMysqlCommandHelp() {
	output, err := test.ExecuteCommand(s.rootCmd, "mysql", "--help")
	s.Require().NoError(err)
	s.Contains(output, "Check MySQL connection")
	s.Contains(output, "DSN")
}

// TestMysqlCommandExample tests the MySQL command example
func (s *MySQLCommandSuite) TestMysqlCommandExample() {
	// The example should be present in the command
	s.Contains(s.mysqlCmd.Example, "wait4x mysql user:password@tcp(localhost:5555)/dbname?tls=skip-verify")
	s.Contains(s.mysqlCmd.Example, "wait4x mysql username:password@unix(/tmp/mysql.sock)/myDatabase")
}

// TestMySQLCommandSuite runs the MySQL command test suite
func TestMySQLCommandSuite(t *testing.T) {
	suite.Run(t, new(MySQLCommandSuite))
}