forked from dotnet/SqlClient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSqlConnectionBasicTests.cs
496 lines (438 loc) · 19.7 KB
/
SqlConnectionBasicTests.cs
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SqlServer.TDS.PreLogin;
using Microsoft.SqlServer.TDS.Servers;
using Xunit;
namespace Microsoft.Data.SqlClient.Tests
{
public class SqlConnectionBasicTests
{
[Fact]
public void ConnectionTest()
{
using TestTdsServer server = TestTdsServer.StartTestServer();
using SqlConnection connection = new SqlConnection(server.ConnectionString);
connection.Open();
}
[ConditionalFact(typeof(TestUtility), nameof(TestUtility.IsNotArmProcess))]
[PlatformSpecific(TestPlatforms.Windows)]
public void IntegratedAuthConnectionTest()
{
using TestTdsServer server = TestTdsServer.StartTestServer();
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(server.ConnectionString);
builder.IntegratedSecurity = true;
using SqlConnection connection = new SqlConnection(builder.ConnectionString);
connection.Open();
}
/// <summary>
/// Runs a test where TDS Server doesn't send encryption info during pre-login response.
/// The driver is expected to fail when that happens, and terminate the connection during pre-login phase
/// when client enables encryption using Encrypt=true or uses default encryption setting.
/// </summary>
[Fact]
public async Task PreLoginEncryptionExcludedTest()
{
using TestTdsServer server = TestTdsServer.StartTestServer(false, false, 5, excludeEncryption: true);
SqlConnectionStringBuilder builder = new(server.ConnectionString)
{
IntegratedSecurity = true
};
using SqlConnection connection = new(builder.ConnectionString);
Exception ex = await Assert.ThrowsAsync<SqlException>(async () => await connection.OpenAsync());
Assert.Contains("The instance of SQL Server you attempted to connect to does not support encryption.", ex.Message, StringComparison.OrdinalIgnoreCase);
}
[ConditionalTheory(typeof(TestUtility), nameof(TestUtility.IsNotArmProcess))]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
[PlatformSpecific(TestPlatforms.Windows)]
public async Task TransientFaultTestAsync(uint errorCode)
{
using TransientFaultTDSServer server = TransientFaultTDSServer.StartTestServer(true, false, errorCode);
SqlConnectionStringBuilder builder = new()
{
DataSource = "localhost," + server.Port,
IntegratedSecurity = true,
Encrypt = SqlConnectionEncryptOption.Optional
};
using SqlConnection connection = new(builder.ConnectionString);
await connection.OpenAsync();
Assert.Equal(ConnectionState.Open, connection.State);
}
[ConditionalTheory(typeof(TestUtility), nameof(TestUtility.IsNotArmProcess))]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
[PlatformSpecific(TestPlatforms.Windows)]
public void TransientFaultTest(uint errorCode)
{
using TransientFaultTDSServer server = TransientFaultTDSServer.StartTestServer(true, false, errorCode);
SqlConnectionStringBuilder builder = new()
{
DataSource = "localhost," + server.Port,
IntegratedSecurity = true,
Encrypt = SqlConnectionEncryptOption.Optional
};
using SqlConnection connection = new(builder.ConnectionString);
try
{
connection.Open();
Assert.Equal(ConnectionState.Open, connection.State);
}
catch (Exception e)
{
Assert.Fail(e.Message);
}
}
[ConditionalTheory(typeof(TestUtility), nameof(TestUtility.IsNotArmProcess))]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
[PlatformSpecific(TestPlatforms.Windows)]
public void TransientFaultDisabledTestAsync(uint errorCode)
{
using TransientFaultTDSServer server = TransientFaultTDSServer.StartTestServer(true, false, errorCode);
SqlConnectionStringBuilder builder = new()
{
DataSource = "localhost," + server.Port,
IntegratedSecurity = true,
ConnectRetryCount = 0,
Encrypt = SqlConnectionEncryptOption.Optional
};
using SqlConnection connection = new(builder.ConnectionString);
Task<SqlException> e = Assert.ThrowsAsync<SqlException>(async () => await connection.OpenAsync());
Assert.Equal(20, e.Result.Class);
Assert.Equal(ConnectionState.Closed, connection.State);
}
[ConditionalTheory(typeof(TestUtility), nameof(TestUtility.IsNotArmProcess))]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
[PlatformSpecific(TestPlatforms.Windows)]
public void TransientFaultDisabledTest(uint errorCode)
{
using TransientFaultTDSServer server = TransientFaultTDSServer.StartTestServer(true, false, errorCode);
SqlConnectionStringBuilder builder = new()
{
DataSource = "localhost," + server.Port,
IntegratedSecurity = true,
ConnectRetryCount = 0,
Encrypt = SqlConnectionEncryptOption.Optional
};
using SqlConnection connection = new(builder.ConnectionString);
SqlException e = Assert.Throws<SqlException>(() => connection.Open());
Assert.Equal(20, e.Class);
Assert.Equal(ConnectionState.Closed, connection.State);
}
[Fact]
public void SqlConnectionDbProviderFactoryTest()
{
SqlConnection con = new();
PropertyInfo dbProviderFactoryProperty = con.GetType().GetProperty("DbProviderFactory", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(dbProviderFactoryProperty);
DbProviderFactory factory = dbProviderFactoryProperty.GetValue(con) as DbProviderFactory;
Assert.NotNull(factory);
Assert.Same(typeof(SqlClientFactory), factory.GetType());
Assert.Same(SqlClientFactory.Instance, factory);
}
[Fact]
public void SqlConnectionValidParameters()
{
var con = new SqlConnection("Timeout=1234;packet Size=5678 ;;; ;");
Assert.Equal(1234, con.ConnectionTimeout);
Assert.Equal(5678, con.PacketSize);
}
[Fact]
public void SqlConnectionEmptyParameters()
{
var con = new SqlConnection("Timeout=;packet Size= ;Integrated Security=;");
//default values are defined in internal class DbConnectionStringDefaults
Assert.Equal(15, con.ConnectionTimeout);
Assert.Equal(8000, con.PacketSize);
Assert.False(new SqlConnectionStringBuilder(con.ConnectionString).IntegratedSecurity);
}
[Theory]
[InlineData("Timeout=null;")]
[InlineData("Timeout= null;")]
[InlineData("Timeout=1 1;")]
[InlineData("Timeout=1a;")]
[InlineData("Integrated Security=truee")]
public void SqlConnectionInvalidParameters(string connString)
{
Assert.Throws<ArgumentException>(() => new SqlConnection(connString));
}
[Fact]
public void ClosedConnectionSchemaRetrieval()
{
using SqlConnection connection = new(string.Empty);
Assert.Throws<InvalidOperationException>(() => connection.GetSchema());
}
[Theory]
[InlineData("RandomStringForTargetServer", false, true)]
[InlineData("RandomStringForTargetServer", true, false)]
[InlineData(null, false, false)]
[InlineData("", false, false)]
public void RetrieveWorkstationId(string workstation, bool withDispose, bool shouldMatchSetWorkstationId)
{
string connectionString = $"Workstation Id={workstation}";
SqlConnection conn = new(connectionString);
if (withDispose)
{
conn.Dispose();
}
string expected = shouldMatchSetWorkstationId ? workstation : Environment.MachineName;
Assert.Equal(expected, conn.WorkstationId);
}
[OuterLoop("Can take up to 4 seconds")]
[Fact]
public void ExceptionsWithMinPoolSizeCanBeHandled()
{
string connectionString = $"Data Source={Guid.NewGuid()};uid=random;pwd=asd;Connect Timeout=2; Min Pool Size=3";
for (int i = 0; i < 2; i++)
{
using SqlConnection connection = new(connectionString);
Exception exception = Record.Exception(() => connection.Open());
Assert.True(exception is InvalidOperationException || exception is SqlException, $"Unexpected exception: {exception}");
}
}
[Fact]
public void ConnectionTestInvalidCredentialCombination()
{
var cleartextCredsConnStr = "User=test;Password=test;";
var sspiConnStr = "Integrated Security=true;";
var testPassword = new SecureString();
testPassword.MakeReadOnly();
var sqlCredential = new SqlCredential(string.Empty, testPassword);
// Verify that SSPI and cleartext username/password are not in the connection string.
Assert.Throws<ArgumentException>(() => { new SqlConnection(cleartextCredsConnStr, sqlCredential); });
Assert.Throws<ArgumentException>(() => { new SqlConnection(sspiConnStr, sqlCredential); });
// Verify that credential may not be set with cleartext username/password or SSPI.
using (var conn = new SqlConnection(cleartextCredsConnStr))
{
Assert.Throws<InvalidOperationException>(() => { conn.Credential = sqlCredential; });
}
using (var conn = new SqlConnection(sspiConnStr))
{
Assert.Throws<InvalidOperationException>(() => { conn.Credential = sqlCredential; });
}
// Verify that connection string with username/password or SSPI may not be set with credential present.
using (var conn = new SqlConnection(string.Empty, sqlCredential))
{
Assert.Throws<InvalidOperationException>(() => { conn.ConnectionString = cleartextCredsConnStr; });
Assert.Throws<InvalidOperationException>(() => { conn.ConnectionString = sspiConnStr; });
}
}
[Theory]
[InlineData(SqlAuthenticationMethod.ActiveDirectoryIntegrated)]
[InlineData(SqlAuthenticationMethod.ActiveDirectoryInteractive)]
[InlineData(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow)]
[InlineData(SqlAuthenticationMethod.ActiveDirectoryManagedIdentity)]
[InlineData(SqlAuthenticationMethod.ActiveDirectoryMSI)]
[InlineData(SqlAuthenticationMethod.ActiveDirectoryDefault)]
[InlineData(SqlAuthenticationMethod.ActiveDirectoryWorkloadIdentity)]
public void ConnectionTestInvalidCredentialAndAuthentication(SqlAuthenticationMethod authentication)
{
var connectionString = $"Authentication={authentication}";
using var testPassword = new SecureString();
testPassword.MakeReadOnly();
var credential = new SqlCredential(string.Empty, testPassword);
Assert.Throws<ArgumentException>(() => new SqlConnection(connectionString, credential));
// Attempt to set the credential after creation
using var connection = new SqlConnection(connectionString);
Assert.Throws<InvalidOperationException>(() => connection.Credential = credential);
}
[Fact]
public void ConnectionTestValidCredentialCombination()
{
var testPassword = new SecureString();
testPassword.MakeReadOnly();
var sqlCredential = new SqlCredential(string.Empty, testPassword);
var conn = new SqlConnection(string.Empty, sqlCredential);
Assert.Equal(sqlCredential, conn.Credential);
}
[Theory]
[InlineData(60)]
[InlineData(30)]
[InlineData(15)]
[InlineData(10)]
[InlineData(5)]
[InlineData(1)]
public void ConnectionTimeoutTest(int timeout)
{
// Start a server with connection timeout from the inline data.
using TestTdsServer server = TestTdsServer.StartTestServer(false, false, timeout);
using SqlConnection connection = new SqlConnection(server.ConnectionString);
// Dispose the server to force connection timeout
server.Dispose();
// Measure the actual time it took to timeout and compare it with configured timeout
Stopwatch timer = new();
Exception ex = null;
// Open a connection with the server disposed.
try
{
timer.Start();
connection.Open();
}
catch (Exception e)
{
timer.Stop();
ex = e;
}
Assert.False(timer.IsRunning, "Timer must be stopped.");
Assert.NotNull(ex);
Assert.True(timer.Elapsed.TotalSeconds <= timeout + 3,
$"The actual timeout {timer.Elapsed.TotalSeconds} is expected to be less than {timeout} plus 3 seconds additional threshold." +
$"{Environment.NewLine}{ex}");
}
[Theory]
[InlineData(60)]
[InlineData(30)]
[InlineData(15)]
[InlineData(10)]
[InlineData(5)]
[InlineData(1)]
public async Task ConnectionTimeoutTestAsync(int timeout)
{
// Start a server with connection timeout from the inline data.
using TestTdsServer server = TestTdsServer.StartTestServer(false, false, timeout);
using SqlConnection connection = new SqlConnection(server.ConnectionString);
// Dispose the server to force connection timeout
server.Dispose();
// Measure the actual time it took to timeout and compare it with configured timeout
Stopwatch timer = new();
Exception ex = null;
// Open a connection with the server disposed.
try
{
//an asyn call with a timeout token to cancel the operation after the specific time
using CancellationTokenSource cts = new CancellationTokenSource(timeout * 1000);
timer.Start();
await connection.OpenAsync(cts.Token).ConfigureAwait(false);
}
catch (Exception e)
{
timer.Stop();
ex = e;
}
Assert.False(timer.IsRunning, "Timer must be stopped.");
Assert.NotNull(ex);
Assert.True(timer.Elapsed.TotalSeconds <= timeout + 3,
$"The actual timeout {timer.Elapsed.TotalSeconds} is expected to be less than {timeout} plus 3 seconds additional threshold." +
$"{Environment.NewLine}{ex}");
}
[Fact]
public void ConnectionInvalidTimeoutTest()
{
Assert.Throws<ArgumentException>(() =>
{
using TestTdsServer server = TestTdsServer.StartTestServer(false, false, -5);
});
}
[Fact]
public void ConnectionTestWithCultureTH()
{
CultureInfo savedCulture = Thread.CurrentThread.CurrentCulture;
CultureInfo savedUICulture = Thread.CurrentThread.CurrentUICulture;
try
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("th-TH");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("th-TH");
using TestTdsServer server = TestTdsServer.StartTestServer();
using SqlConnection connection = new SqlConnection(server.ConnectionString);
connection.Open();
Assert.Equal(ConnectionState.Open, connection.State);
}
finally
{
// Restore saved cultures if necessary
if (Thread.CurrentThread.CurrentCulture != savedCulture)
Thread.CurrentThread.CurrentCulture = savedCulture;
if (Thread.CurrentThread.CurrentUICulture != savedUICulture)
Thread.CurrentThread.CurrentUICulture = savedUICulture;
}
}
[Fact]
public void ConnectionTestAccessTokenCallbackCombinations()
{
var cleartextCredsConnStr = "User=test;Password=test;";
var sspiConnStr = "Integrated Security=true;";
var authConnStr = "Authentication=ActiveDirectoryPassword";
var testPassword = new SecureString();
testPassword.MakeReadOnly();
var sqlCredential = new SqlCredential(string.Empty, testPassword);
Func<SqlAuthenticationParameters, CancellationToken, Task<SqlAuthenticationToken>> callback = (ctx, token) =>
Task.FromResult(new SqlAuthenticationToken("invalid", DateTimeOffset.MaxValue));
// Successes
using (var conn = new SqlConnection(cleartextCredsConnStr))
{
conn.AccessTokenCallback = callback;
conn.AccessTokenCallback = null;
}
using (var conn = new SqlConnection(string.Empty, sqlCredential))
{
conn.AccessTokenCallback = null;
conn.AccessTokenCallback = callback;
}
using (var conn = new SqlConnection()
{
AccessTokenCallback = callback
})
{
conn.Credential = sqlCredential;
}
using (var conn = new SqlConnection()
{
AccessTokenCallback = callback
})
{
conn.ConnectionString = cleartextCredsConnStr;
}
//Failures
using (var conn = new SqlConnection(sspiConnStr))
{
Assert.Throws<InvalidOperationException>(() =>
{
conn.AccessTokenCallback = callback;
});
}
using (var conn = new SqlConnection(authConnStr))
{
Assert.Throws<InvalidOperationException>(() =>
{
conn.AccessTokenCallback = callback;
});
}
using (var conn = new SqlConnection()
{
AccessTokenCallback = callback
})
{
Assert.Throws<InvalidOperationException>(() =>
{
conn.ConnectionString = sspiConnStr;
});
}
using (var conn = new SqlConnection()
{
AccessTokenCallback = callback
})
{
Assert.Throws<InvalidOperationException>(() =>
{
conn.ConnectionString = authConnStr;
});
}
}
}
}