forked from dotnet/SqlClient
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSqlConnectionBasicTests.cs
211 lines (188 loc) · 8.76 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
// 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.Reflection;
using System.Security;
using System.Threading.Tasks;
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(PlatformDetection), nameof(PlatformDetection.IsNotArmProcess))]
[ActiveIssue(4830, TestPlatforms.AnyUnix)]
[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(PlatformDetection), nameof(PlatformDetection.IsNotArmProcess))]
[InlineData(40613)]
[InlineData(42108)]
[InlineData(42109)]
[PlatformSpecific(TestPlatforms.Windows)]
public void TransientFaultTest(uint errorCode)
{
using TransientFaultTDSServer server = TransientFaultTDSServer.StartTestServer(true, true, 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)
{
if (null != connection)
{
Assert.Equal(ConnectionState.Closed, connection.State);
}
Assert.False(true, e.Message);
}
}
[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; });
}
}
[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);
}
}
}