diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs index 3b4245d84f..5bceb81b58 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs @@ -302,9 +302,9 @@ private static Task AcquireTokenAsync(string authorityURL, string userID SecureString securePassword = new SecureString(); securePassword.MakeReadOnly(); -#pragma warning disable CS0618 // Type or member is obsolete + #pragma warning disable CS0618 // Type or member is obsolete result = app.AcquireTokenByUsernamePassword(scopes, userID, password).ExecuteAsync().Result; -#pragma warning restore CS0618 // Type or member is obsolete + #pragma warning restore CS0618 // Type or member is obsolete return result.AccessToken; }); @@ -389,7 +389,7 @@ public static string GetSqlServerProperty(SqlConnection connection, ServerProper } } - #nullable disable + #nullable restore private static bool GetSQLServerStatusOnTDS8(string connectionString) { @@ -951,35 +951,48 @@ public static void AssertEqualsWithDescription(object expectedValue, object actu } } - public static TException AssertThrowsWrapper(Action actionThatFails, string exceptionMessage = null, bool innerExceptionMustBeNull = false, Func customExceptionVerifier = null) where TException : Exception + #nullable enable + + /// + /// Asserts that throws an exception of type + /// and optionally verifies that its message contains + /// . + /// + public static TException AssertThrows( + Action actionThatFails, + string? exceptionMessage = null) + where TException : Exception { TException ex = Assert.Throws(actionThatFails); + if (exceptionMessage != null) { Assert.True(ex.Message.Contains(exceptionMessage), string.Format("FAILED: Exception did not contain expected message.\nExpected: {0}\nActual: {1}", exceptionMessage, ex.Message)); } - if (innerExceptionMustBeNull) - { - Assert.True(ex.InnerException == null, "FAILED: Expected InnerException to be null."); - } - - if (customExceptionVerifier != null) - { - Assert.True(customExceptionVerifier(ex), "FAILED: Custom exception verifier returned false for this exception."); - } - return ex; } - public static TException AssertThrowsWrapper(Action actionThatFails, string exceptionMessage = null, string innerExceptionMessage = null, bool innerExceptionMustBeNull = false, Func customExceptionVerifier = null) where TException : Exception + /// + /// Asserts that throws + /// whose is of type . + /// Optionally verifies message text on both the outer and inner exceptions. + /// + public static TException AssertThrowsInner( + Action actionThatFails, + string? exceptionMessage = null, + string? innerExceptionMessage = null) + where TException : Exception + where TInnerException : Exception { - TException ex = AssertThrowsWrapper(actionThatFails, exceptionMessage, innerExceptionMustBeNull, customExceptionVerifier); + TException ex = AssertThrows(actionThatFails, exceptionMessage); + + Assert.NotNull(ex.InnerException); + Assert.IsAssignableFrom(ex.InnerException); if (innerExceptionMessage != null) { - Assert.True(ex.InnerException != null, "FAILED: Cannot check innerExceptionMessage because InnerException is null."); Assert.True(ex.InnerException.Message.Contains(innerExceptionMessage), string.Format("FAILED: Inner Exception did not contain expected message.\nExpected: {0}\nActual: {1}", innerExceptionMessage, ex.InnerException.Message)); } @@ -987,26 +1000,40 @@ public static TException AssertThrowsWrapper(Action return ex; } - public static TException AssertThrowsWrapper(Action actionThatFails, string exceptionMessage = null, string innerExceptionMessage = null, string innerInnerExceptionMessage = null, bool innerInnerInnerExceptionMustBeNull = false) where TException : Exception where TInnerException : Exception where TInnerInnerException : Exception + /// + /// Asserts that throws + /// whose is either + /// or . Use this when a race condition + /// (e.g. disposal during an async read) may cause the inner exception type to vary + /// between runs. The is only verified when the + /// inner exception is . + /// + public static TException AssertThrowsInnerWithAlternate( + Action actionThatFails, + string? exceptionMessage = null, + string? innerExceptionMessage = null) + where TException : Exception + where TInnerException : Exception + where TAlternateInnerException : Exception { - TException ex = AssertThrowsWrapper(actionThatFails, exceptionMessage, innerExceptionMessage); - if (innerInnerInnerExceptionMustBeNull) - { - Assert.True(ex.InnerException != null, "FAILED: Cannot check innerInnerInnerExceptionMustBeNull since InnerException is null"); - Assert.True(ex.InnerException.InnerException == null, "FAILED: Expected InnerInnerException to be null."); - } + TException ex = AssertThrows(actionThatFails, exceptionMessage); - if (innerInnerExceptionMessage != null) + Assert.NotNull(ex.InnerException); + Assert.True( + ex.InnerException is TInnerException or TAlternateInnerException, + $"Expected {typeof(TInnerException).Name} or {typeof(TAlternateInnerException).Name}, got: {ex.InnerException?.GetType()}"); + + if (innerExceptionMessage != null && ex.InnerException is TInnerException) { - Assert.True(ex.InnerException != null, "FAILED: Cannot check innerInnerExceptionMessage since InnerException is null"); - Assert.True(ex.InnerException.InnerException != null, "FAILED: Cannot check innerInnerExceptionMessage since InnerInnerException is null"); - Assert.True(ex.InnerException.InnerException.Message.Contains(innerInnerExceptionMessage), - string.Format("FAILED: Inner Exception did not contain expected message.\nExpected: {0}\nActual: {1}", innerInnerExceptionMessage, ex.InnerException.InnerException.Message)); + Assert.True(ex.InnerException.Message.Contains(innerExceptionMessage), + string.Format("FAILED: Inner Exception did not contain expected message.\nExpected: {0}\nActual: {1}", innerExceptionMessage, ex.InnerException.Message)); } return ex; } + #nullable restore + public static TException ExpectFailure(Action actionThatFails, string[] exceptionMessages, bool innerExceptionMustBeNull = false, Func customExceptionVerifier = null) where TException : Exception { try @@ -1320,7 +1347,7 @@ public static string GetMachineFQDN(string hostname) } return fqdn.ToString(); } - } - #nullable disable + #nullable restore + } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs index ed9d9ab541..9bf5351a83 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs @@ -1318,13 +1318,13 @@ public void TestDeriveParameters() using (SqlCommand cmd = new SqlCommand(procName, connection)) { string errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_DeriveParametersNotSupported, "SqlCommand", cmd.CommandType); - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => SqlCommandBuilder.DeriveParameters(cmd), errorMessage); errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_OpenConnectionRequired, "DeriveParameters", ""); cmd.CommandType = CommandType.StoredProcedure; - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => SqlCommandBuilder.DeriveParameters(cmd), errorMessage); @@ -1335,7 +1335,7 @@ public void TestDeriveParameters() cmd.CommandText = "Test_EmployeeSalesBy"; errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NoStoredProcedureExists, cmd.CommandText); - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => SqlCommandBuilder.DeriveParameters(cmd), errorMessage); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataStreamTest/DataStreamTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataStreamTest/DataStreamTest.cs index 1c6d851ecc..2de13c98ac 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataStreamTest/DataStreamTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataStreamTest/DataStreamTest.cs @@ -276,7 +276,7 @@ static async Task LocalCopyTo(Stream source, Stream destination, int bufferSize, { await destination.WriteAsync(new ReadOnlyMemory(buffer, 0, bytesRead), cancellationToken).ConfigureAwait(false); } -#endif +#endif } finally { @@ -320,7 +320,7 @@ private static byte[] CreateBinaryTable(SqlConnection connection, string tableNa { cmd.CommandText = $@" IF OBJECT_ID('dbo.{tableName}', 'U') IS NOT NULL -DROP TABLE {tableName}; +DROP TABLE {tableName}; CREATE TABLE {tableName} (id INT, foo VARBINARY(MAX)) "; cmd.ExecuteNonQuery(); @@ -377,7 +377,7 @@ private static void MultipleResults(string connectionString) { Assert.True(numBatches < expectedResults.Length, "ERROR: Received more batches than were expected."); object[] values = new object[r1.FieldCount]; - // Current "column" in expected row is (valuesChecked MOD FieldCount), since + // Current "column" in expected row is (valuesChecked MOD FieldCount), since // expected rows for current batch are appended together for easy formatting int valuesChecked = 0; while (r1.Read()) @@ -410,7 +410,7 @@ private static void InvalidRead(string connectionString) using (SqlDataReader reader = cmd.ExecuteReader()) { string errorMessage = SystemDataResourceManager.Instance.SQL_InvalidRead; - DataTestUtility.AssertThrowsWrapper(() => reader.GetInt32(0), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetInt32(0), errorMessage); } } } @@ -497,7 +497,7 @@ private static void TypeRead(string connectionString) s = rdr.GetString(10); //ShipCity; // should get an exception here string errorMessage = SystemDataResourceManager.Instance.SqlMisc_NullValueMessage; - DataTestUtility.AssertThrowsWrapper(() => rdr.GetString(11), errorMessage); + DataTestUtility.AssertThrows(() => rdr.GetString(11), errorMessage); s = rdr.GetString(12); //ShipPostalCode; s = rdr.GetString(13); //ShipCountry; @@ -533,7 +533,7 @@ private static void GetValueOfTRead(string connectionString) rdr.IsDBNull(10); rdr.GetFieldValue(10); //ShipCity; // should get an exception here - DataTestUtility.AssertThrowsWrapper(() => rdr.GetFieldValue(11), errorMessage); + DataTestUtility.AssertThrows(() => rdr.GetFieldValue(11), errorMessage); rdr.IsDBNull(11); rdr.GetFieldValue(11); rdr.IsDBNull(11); @@ -542,7 +542,7 @@ private static void GetValueOfTRead(string connectionString) rdr.IsDBNull(12); rdr.GetFieldValue(13);//ShipCountry; rdr.GetFieldValue(14); - DataTestUtility.AssertThrowsWrapper(() => rdr.GetFieldValue(15), errorMessage); + DataTestUtility.AssertThrows(() => rdr.GetFieldValue(15), errorMessage); rdr.Read(); // read data out of buffer @@ -559,7 +559,7 @@ private static void GetValueOfTRead(string connectionString) Assert.False(rdr.IsDBNullAsync(10).Result, "FAILED: IsDBNull was true for a non-null value"); rdr.GetFieldValueAsync(10).Wait(); //ShipCity; // should get an exception here - DataTestUtility.AssertThrowsWrapper(() => rdr.GetFieldValueAsync(11).Wait(), innerExceptionMessage: errorMessage); + DataTestUtility.AssertThrowsInner(() => rdr.GetFieldValueAsync(11).Wait(), innerExceptionMessage: errorMessage); Assert.True(rdr.IsDBNullAsync(11).Result, "FAILED: IsDBNull was false for a null value"); rdr.IsDBNullAsync(11).Wait(); @@ -787,7 +787,7 @@ private static void OrphanReader(string connectionString) conn.Close(); errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_DataReaderClosed, "CheckDataIsReady"); - DataTestUtility.AssertThrowsWrapper(() => value = reader[0], errorMessage); + DataTestUtility.AssertThrows(() => value = reader[0], errorMessage); Assert.True(reader.IsClosed, "FAILED: Stream was not closed by connection close (Scenario: Read)"); conn.Open(); } @@ -798,7 +798,7 @@ private static void OrphanReader(string connectionString) value = reader[0]; conn.Close(); - DataTestUtility.AssertThrowsWrapper(() => value = reader[0], errorMessage); + DataTestUtility.AssertThrows(() => value = reader[0], errorMessage); Assert.True(reader.IsClosed, "FAILED: Stream was not closed by connection close (Scenario: Read Partial Data)"); conn.Open(); } @@ -817,7 +817,7 @@ private static void OrphanReader(string connectionString) } while (reader.NextResult()); conn.Close(); - DataTestUtility.AssertThrowsWrapper(() => value = reader[0], errorMessage); + DataTestUtility.AssertThrows(() => value = reader[0], errorMessage); Assert.True(reader.IsClosed, "FAILED: Stream was not closed by connection close (Scenario: Read All Data)"); } } @@ -866,7 +866,7 @@ private static void ExecuteXmlReaderTest(string connectionString) // make sure we get an exception if we try to get another reader errorMessage = SystemDataResourceManager.Instance.ADP_OpenReaderExists("Connection"); - DataTestUtility.AssertThrowsWrapper(() => xr = cmd.ExecuteXmlReader(), errorMessage); + DataTestUtility.AssertThrows(() => xr = cmd.ExecuteXmlReader(), errorMessage); } // use a big result to fill up the pipe and do a partial read @@ -943,12 +943,12 @@ private static void ExecuteXmlReaderTest(string connectionString) // multiple columns cmd.CommandText = "select * from customers"; errorMessage = SystemDataResourceManager.Instance.SQL_NonXmlResult; - DataTestUtility.AssertThrowsWrapper(() => xr = cmd.ExecuteXmlReader(), errorMessage); + DataTestUtility.AssertThrows(() => xr = cmd.ExecuteXmlReader(), errorMessage); // non-ntext column cmd.CommandText = "select employeeID from employees"; errorMessage = SystemDataResourceManager.Instance.SQL_NonXmlResult; - DataTestUtility.AssertThrowsWrapper(() => xr = cmd.ExecuteXmlReader(), errorMessage); + DataTestUtility.AssertThrows(() => xr = cmd.ExecuteXmlReader(), errorMessage); } } } @@ -1114,31 +1114,31 @@ private static void SequentialAccess(string connectionString) i = reader.GetOrdinal("notes"); reader.GetChars(i, 14, chars, 0, 14); string errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSequentialColumnAccess, i, i + 1); - DataTestUtility.AssertThrowsWrapper(() => reader.GetString(i), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetString(i), errorMessage); // Tests GetValue before GetBytes\Chars reader.Read(); i = reader.GetOrdinal("photo"); reader.GetSqlBinary(i); errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSequentialColumnAccess, i, i + 1); - DataTestUtility.AssertThrowsWrapper(() => reader.GetBytes(i, 0, data, 0, 13), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetBytes(i, 0, data, 0, 13), errorMessage); i = reader.GetOrdinal("notes"); reader.GetString(i); errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSequentialColumnAccess, i, i + 1); - DataTestUtility.AssertThrowsWrapper(() => reader.GetChars(i, 0, chars, 0, 14), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetChars(i, 0, chars, 0, 14), errorMessage); // Tests GetBytes\GetChars re-reading same characters reader.Read(); i = reader.GetOrdinal("photo"); reader.GetBytes(i, 0, data, 0, 13); errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSeqByteAccess, 0, 13, "GetBytes"); - DataTestUtility.AssertThrowsWrapper(() => reader.GetBytes(i, 0, data, 0, 13), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetBytes(i, 0, data, 0, 13), errorMessage); i = reader.GetOrdinal("notes"); reader.GetChars(i, 0, chars, 0, 14); errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSeqByteAccess, 0, 14, "GetChars"); - DataTestUtility.AssertThrowsWrapper(() => reader.GetChars(i, 0, chars, 0, 14), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetChars(i, 0, chars, 0, 14), errorMessage); } using (reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) @@ -1150,12 +1150,12 @@ private static void SequentialAccess(string connectionString) int columnToTry = 0; string errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSequentialColumnAccess, columnToTry, sqldata.Length); - DataTestUtility.AssertThrowsWrapper(() => reader.GetInt32(columnToTry), errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetValue(columnToTry), errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetFieldValue(columnToTry), errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetFieldValue(columnToTry), errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetFieldValueAsync(columnToTry).Wait(), innerExceptionMessage: errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetFieldValueAsync(columnToTry).Wait(), innerExceptionMessage: errorMessage); + DataTestUtility.AssertThrows(() => reader.GetInt32(columnToTry), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetValue(columnToTry), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetFieldValue(columnToTry), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetFieldValue(columnToTry), errorMessage); + DataTestUtility.AssertThrowsInner(() => reader.GetFieldValueAsync(columnToTry).Wait(), innerExceptionMessage: errorMessage); + DataTestUtility.AssertThrowsInner(() => reader.GetFieldValueAsync(columnToTry).Wait(), innerExceptionMessage: errorMessage); reader.Read(); columnToTry = 17; @@ -1163,12 +1163,12 @@ private static void SequentialAccess(string connectionString) s = reader.GetString(columnToTry); DataTestUtility.AssertEqualsWithDescription("http://accweb/emmployees/fuller.bmp", s, "FAILED: Did not receive expected string."); - DataTestUtility.AssertThrowsWrapper(() => reader.GetInt32(columnToTry), errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetValue(columnToTry), errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetFieldValue(columnToTry), errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetFieldValue(columnToTry), errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetFieldValueAsync(columnToTry).Wait(), innerExceptionMessage: errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetFieldValueAsync(columnToTry).Wait(), innerExceptionMessage: errorMessage); + DataTestUtility.AssertThrows(() => reader.GetInt32(columnToTry), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetValue(columnToTry), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetFieldValue(columnToTry), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetFieldValue(columnToTry), errorMessage); + DataTestUtility.AssertThrowsInner(() => reader.GetFieldValueAsync(columnToTry).Wait(), innerExceptionMessage: errorMessage); + DataTestUtility.AssertThrowsInner(() => reader.GetFieldValueAsync(columnToTry).Wait(), innerExceptionMessage: errorMessage); reader.Read(); // skip all columns up to photo, and read from it partially @@ -1189,14 +1189,14 @@ private static void SequentialAccess(string connectionString) // now try to read one more byte string errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_DataReaderClosed, "GetBytes"); - DataTestUtility.AssertThrowsWrapper(() => cb = reader.GetBytes(i, 51, data, 0, 1), errorMessage); + DataTestUtility.AssertThrows(() => cb = reader.GetBytes(i, 51, data, 0, 1), errorMessage); errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_DataReaderClosed, "CheckDataIsReady"); - DataTestUtility.AssertThrowsWrapper(() => reader.GetValue(i), errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetFieldValue(i), errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetFieldValue(i), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetValue(i), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetFieldValue(i), errorMessage); + DataTestUtility.AssertThrows(() => reader.GetFieldValue(i), errorMessage); errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_DataReaderClosed, "GetFieldValueAsync"); - DataTestUtility.AssertThrowsWrapper(() => reader.GetFieldValueAsync(i).Wait(), innerExceptionMessage: errorMessage); - DataTestUtility.AssertThrowsWrapper(() => reader.GetFieldValueAsync(i).Wait(), innerExceptionMessage: errorMessage); + DataTestUtility.AssertThrowsInnerWithAlternate(() => reader.GetFieldValueAsync(i).Wait(), innerExceptionMessage: errorMessage); + DataTestUtility.AssertThrowsInnerWithAlternate(() => reader.GetFieldValueAsync(i).Wait(), innerExceptionMessage: errorMessage); } } } @@ -1236,10 +1236,10 @@ private static void NumericRead(string connectionString) // Em object value; string errorMessage = SystemDataResourceManager.Instance.SqlMisc_ConversionOverflowMessage; - DataTestUtility.AssertThrowsWrapper(() => value = reader[0], errorMessage); - DataTestUtility.AssertThrowsWrapper(() => value = reader[1], errorMessage); - DataTestUtility.AssertThrowsWrapper(() => value = reader.GetDecimal(0), errorMessage); - DataTestUtility.AssertThrowsWrapper(() => value = reader.GetDecimal(1), errorMessage); + DataTestUtility.AssertThrows(() => value = reader[0], errorMessage); + DataTestUtility.AssertThrows(() => value = reader[1], errorMessage); + DataTestUtility.AssertThrows(() => value = reader.GetDecimal(0), errorMessage); + DataTestUtility.AssertThrows(() => value = reader.GetDecimal(1), errorMessage); } } finally @@ -1297,7 +1297,7 @@ private static void HasRowsTest(string connectionString) bool result; string errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_DataReaderClosed, "HasRows"); - DataTestUtility.AssertThrowsWrapper(() => result = reader.HasRows, errorMessage); + DataTestUtility.AssertThrows(() => result = reader.HasRows, errorMessage); } } } @@ -1382,7 +1382,7 @@ private static void SeqAccessFailureWrapper(Action action, CommandBe { if (behavior == CommandBehavior.SequentialAccess) { - DataTestUtility.AssertThrowsWrapper(action); + DataTestUtility.AssertThrows(action); } else { @@ -1390,6 +1390,24 @@ private static void SeqAccessFailureWrapper(Action action, CommandBe } } + /// + /// Waits for a task that may or may not throw due to a race condition, and if they do + /// throw, they may throw one of a few acceptable exceptions. + /// + /// See: https://github.com/dotnet/SqlClient/issues/4088 + /// + private static void WaitIgnoringFlakyException(Task task) + { + try { task.Wait(); } + catch (AggregateException) + { + // A faulted Task stores its exception permanently. Calling .Wait() again is + // guaranteed to re-throw the same AggregateException, so we can safely pass it to + // the assert helper for inner-exception validation. + DataTestUtility.AssertThrowsInnerWithAlternate(() => task.Wait()); + } + } + private static void GetStream(string connectionString) { using (SqlConnection connection = new SqlConnection(connectionString)) @@ -1410,7 +1428,7 @@ private static void GetStream(string connectionString) reader.GetStream(1); // Bad values - DataTestUtility.AssertThrowsWrapper(() => reader.GetStream(2)); + DataTestUtility.AssertThrows(() => reader.GetStream(2)); // Null stream Stream stream = reader.GetStream(3); Assert.False(stream.Read(buffer, 0, buffer.Length) > 0, "FAILED: Read more than 0 bytes from a null stream"); @@ -1446,12 +1464,12 @@ private static void GetStream(string connectionString) { t = reader.ReadAsync(); Assert.False(t.Wait(1), "FAILED: Read completed immediately"); - DataTestUtility.AssertThrowsWrapper(() => reader.GetStream(8)); + DataTestUtility.AssertThrows(() => reader.GetStream(8)); } - DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + WaitIgnoringFlakyException(t); - // GetStream after Read - DataTestUtility.AssertThrowsWrapper(() => reader.GetStream(0)); + // GetStream after Read + DataTestUtility.AssertThrows(() => reader.GetStream(0)); #endif } @@ -1486,8 +1504,7 @@ private static void GetStream(string connectionString) Assert.True(t.IsCompleted, "FAILED: Failed to get stream within 1 second"); t = reader.ReadAsync(); } - // TODO(GH-3604): Fix this failing assertion. - // DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + WaitIgnoringFlakyException(t); } #endif } @@ -1523,7 +1540,7 @@ private static void GetTextReader(string connectionString) reader.GetTextReader(1); // Bad values - DataTestUtility.AssertThrowsWrapper(() => reader.GetTextReader(2)); + DataTestUtility.AssertThrows(() => reader.GetTextReader(2)); // Null stream TextReader textReader = reader.GetTextReader(3); Assert.False(textReader.Read(buffer, 0, buffer.Length) > 0, "FAILED: Read more than 0 chars from a null TextReader"); @@ -1559,13 +1576,12 @@ private static void GetTextReader(string connectionString) { t = reader.ReadAsync(); Assert.False(t.IsCompleted, "FAILED: Read completed immediately"); - DataTestUtility.AssertThrowsWrapper(() => reader.GetTextReader(8)); + DataTestUtility.AssertThrows(() => reader.GetTextReader(8)); } - // TODO(GH-3604): Fix this failing assertion. - // DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + WaitIgnoringFlakyException(t); - // GetTextReader after Read - DataTestUtility.AssertThrowsWrapper(() => reader.GetTextReader(0)); + // GetTextReader after Read + DataTestUtility.AssertThrows(() => reader.GetTextReader(0)); #endif } @@ -1601,8 +1617,7 @@ private static void GetTextReader(string connectionString) Assert.True(t.IsCompleted, "FAILED: Failed to get TextReader within 1 second"); t = reader.ReadAsync(); } - // TODO(GH-3604): Fix this failing assertion. - // DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + WaitIgnoringFlakyException(t); } #endif } @@ -1631,7 +1646,7 @@ private static void GetXmlReader(string connectionString) reader.GetXmlReader(1); // Bad values - DataTestUtility.AssertThrowsWrapper(() => reader.GetXmlReader(2)); + DataTestUtility.AssertThrows(() => reader.GetXmlReader(2)); // Null stream XmlReader xmlReader = reader.GetXmlReader(3); Assert.False(xmlReader.Read(), "FAILED: Successfully read on a null XmlReader"); @@ -1651,13 +1666,12 @@ private static void GetXmlReader(string connectionString) { t = reader.ReadAsync(); Assert.False(t.IsCompleted, "FAILED: Read completed immediately"); - DataTestUtility.AssertThrowsWrapper(() => reader.GetXmlReader(6)); + DataTestUtility.AssertThrows(() => reader.GetXmlReader(6)); } - // TODO(GH-3604): Fix this failing assertion. - // DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + WaitIgnoringFlakyException(t); - // GetXmlReader after Read - DataTestUtility.AssertThrowsWrapper(() => reader.GetXmlReader(0)); + // GetXmlReader after Read + DataTestUtility.AssertThrows(() => reader.GetXmlReader(0)); #endif } } @@ -1691,16 +1705,16 @@ private static void ReadStream(string connectionString) // Testing stream properties stream.Flush(); - DataTestUtility.AssertThrowsWrapper(() => stream.SetLength(1)); + DataTestUtility.AssertThrows(() => stream.SetLength(1)); Action performOnStream = ((s) => { int i = s.WriteTimeout; }); - DataTestUtility.AssertThrowsWrapper(() => performOnStream(stream)); + DataTestUtility.AssertThrows(() => performOnStream(stream)); if (behavior == CommandBehavior.SequentialAccess) { - DataTestUtility.AssertThrowsWrapper(() => stream.Seek(0, SeekOrigin.Begin)); + DataTestUtility.AssertThrows(() => stream.Seek(0, SeekOrigin.Begin)); performOnStream = ((s) => { long i = s.Position; }); - DataTestUtility.AssertThrowsWrapper(() => performOnStream(stream)); + DataTestUtility.AssertThrows(() => performOnStream(stream)); performOnStream = ((s) => { long i = s.Length; }); - DataTestUtility.AssertThrowsWrapper(() => performOnStream(stream)); + DataTestUtility.AssertThrows(() => performOnStream(stream)); } else { @@ -1711,7 +1725,7 @@ private static void ReadStream(string connectionString) } // Once Stream is closed - DataTestUtility.AssertThrowsWrapper(() => { _ = stream.Read(buffer, 0, buffer.Length); }); + DataTestUtility.AssertThrows(() => { _ = stream.Read(buffer, 0, buffer.Length); }); } using (SqlDataReader reader = cmd.ExecuteReader(behavior)) @@ -1723,9 +1737,9 @@ private static void ReadStream(string connectionString) _ = stream.Read(buffer, 0, buffer.Length); // Argument exceptions - DataTestUtility.AssertThrowsWrapper(() => { _ = stream.Read(null, 0, 1); }); - DataTestUtility.AssertThrowsWrapper(() => { _ = stream.Read(buffer, -1, 2); }); - DataTestUtility.AssertThrowsWrapper(() => { _ = stream.Read(buffer, 2, -1); }); + DataTestUtility.AssertThrows(() => { _ = stream.Read(null, 0, 1); }); + DataTestUtility.AssertThrows(() => { _ = stream.Read(buffer, -1, 2); }); + DataTestUtility.AssertThrows(() => { _ = stream.Read(buffer, 2, -1); }); // Prior to net6 comment:ArgumentException is thrown in net5 and earlier. ArgumentOutOfRangeException in net6 and later ArgumentException ex = Assert.ThrowsAny(() => { _ = stream.Read(buffer, buffer.Length, buffer.Length); }); @@ -1777,10 +1791,10 @@ private static void ReadStream(string connectionString) { // Read during async t = stream.ReadAsync(largeBuffer, 0, largeBuffer.Length); - DataTestUtility.AssertThrowsWrapper(() => { _ = stream.Read(largeBuffer, 0, largeBuffer.Length); }); - DataTestUtility.AssertThrowsWrapper(() => reader.Read()); + DataTestUtility.AssertThrows(() => { _ = stream.Read(largeBuffer, 0, largeBuffer.Length); }); + DataTestUtility.AssertThrows(() => reader.Read()); } - DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + DataTestUtility.AssertThrowsInnerWithAlternate(() => t.Wait()); } using (SqlDataReader reader = cmd.ExecuteReader(behavior)) { @@ -1796,7 +1810,7 @@ private static void ReadStream(string connectionString) // Guarantee that timeout occurs: Thread.Sleep(stream.ReadTimeout * 4); } - DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + DataTestUtility.AssertThrowsInnerWithAlternate(() => t.Wait()); } using (SqlDataReader reader = cmd.ExecuteReader(behavior)) @@ -1811,7 +1825,10 @@ private static void ReadStream(string connectionString) t = stream.ReadAsync(largeBuffer, 0, largeBuffer.Length, tokenSource.Token); tokenSource.Cancel(); } - DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + // Normally the cancellation wins (TaskCanceledException), but if the + // PendAsyncReadsScope disposal completes the read first, the inner + // exception may be InvalidOperationException instead (GH-4088). + DataTestUtility.AssertThrowsInnerWithAlternate(() => t.Wait()); } using (SqlDataReader reader = cmd.ExecuteReader(behavior)) @@ -1824,7 +1841,18 @@ private static void ReadStream(string connectionString) // Error during read t = stream.ReadAsync(largeBuffer, 0, largeBuffer.Length); } - DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + // PendAsyncReadsScope(errorCode: 11) injects a network error, normally producing + // AggregateException -> IOException -> SqlException. In rare race conditions + // the inner exception may be ObjectDisposedException instead (GH-4088). + AggregateException aex = Assert.Throws(() => t.Wait()); + if (aex.InnerException is IOException ioEx) + { + Assert.IsAssignableFrom(ioEx.InnerException); + } + else + { + Assert.IsAssignableFrom(aex.InnerException); + } } #endif } @@ -1876,7 +1904,7 @@ private static void ReadTextReader(string connectionString) } // Once Reader is closed - DataTestUtility.AssertThrowsWrapper(() => textReader.Read(buffer, 0, buffer.Length)); + DataTestUtility.AssertThrows(() => textReader.Read(buffer, 0, buffer.Length)); } using (SqlDataReader reader = cmd.ExecuteReader(behavior)) @@ -1890,11 +1918,11 @@ private static void ReadTextReader(string connectionString) textReader.Peek(); // Argument exceptions - DataTestUtility.AssertThrowsWrapper(() => textReader.Read(null, 0, 1)); - DataTestUtility.AssertThrowsWrapper(() => textReader.Read(buffer, -1, 2)); - DataTestUtility.AssertThrowsWrapper(() => textReader.Read(buffer, 2, -1)); - DataTestUtility.AssertThrowsWrapper(() => textReader.Read(buffer, buffer.Length, buffer.Length)); - DataTestUtility.AssertThrowsWrapper(() => textReader.Read(buffer, int.MaxValue, int.MaxValue)); + DataTestUtility.AssertThrows(() => textReader.Read(null, 0, 1)); + DataTestUtility.AssertThrows(() => textReader.Read(buffer, -1, 2)); + DataTestUtility.AssertThrows(() => textReader.Read(buffer, 2, -1)); + DataTestUtility.AssertThrows(() => textReader.Read(buffer, buffer.Length, buffer.Length)); + DataTestUtility.AssertThrows(() => textReader.Read(buffer, int.MaxValue, int.MaxValue)); } // Once Reader is closed @@ -1936,11 +1964,10 @@ private static void ReadTextReader(string connectionString) { // Read during async t = textReader.ReadAsync(largeBuffer, 0, largeBuffer.Length); - DataTestUtility.AssertThrowsWrapper(() => textReader.Read(largeBuffer, 0, largeBuffer.Length)); - DataTestUtility.AssertThrowsWrapper(() => reader.Read()); + DataTestUtility.AssertThrows(() => textReader.Read(largeBuffer, 0, largeBuffer.Length)); + DataTestUtility.AssertThrows(() => reader.Read()); } - // TODO(GH-3604): Fix this failing assertion. - // DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + WaitIgnoringFlakyException(t); } using (SqlDataReader reader = cmd.ExecuteReader(behavior)) @@ -1953,7 +1980,18 @@ private static void ReadTextReader(string connectionString) // Error during read t = textReader.ReadAsync(largeBuffer, 0, largeBuffer.Length); } - DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + // PendAsyncReadsScope(errorCode: 11) injects a network error, normally producing + // AggregateException -> IOException -> SqlException. In rare race conditions + // the inner exception may be ObjectDisposedException instead (GH-4088). + AggregateException aex = Assert.Throws(() => t.Wait()); + if (aex.InnerException is IOException ioEx) + { + Assert.IsAssignableFrom(ioEx.InnerException); + } + else + { + Assert.IsAssignableFrom(aex.InnerException); + } } #endif } @@ -2118,7 +2156,7 @@ private void TestXEventsStreaming(string connectionString) byte[] bytes = new byte[cb]; long read = reader.GetBytes(1, 0, bytes, 0, cb); - // Don't send data on the first read because there is already data in the buffer. + // Don't send data on the first read because there is already data in the buffer. // Don't send data on the last iteration. We will not be reading that data. if (i == 0 || i == streamXeventCount - 1) { @@ -2164,7 +2202,7 @@ private static void TimeoutDuringReadAsyncWithClosedReaderTest(string connection // Wait for the task to see the timeout string errorMessage = SystemDataResourceManager.Instance.SQL_Timeout_Execution; - DataTestUtility.AssertThrowsWrapper(() => task.Wait(), innerExceptionMessage: errorMessage); + DataTestUtility.AssertThrowsInnerWithAlternate(() => task.Wait(), innerExceptionMessage: errorMessage); } } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/LocalDBTest/LocalDBTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/LocalDBTest/LocalDBTest.cs index ad84ac7881..c3aed471c0 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/LocalDBTest/LocalDBTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/LocalDBTest/LocalDBTest.cs @@ -54,7 +54,7 @@ public static void LocalDBMarsTest() public static void InvalidLocalDBTest() { using var connection = new SqlConnection(s_badConnectionString); - DataTestUtility.AssertThrowsWrapper(() => connection.Open()); + DataTestUtility.AssertThrows(() => connection.Open()); } #endregion diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MARSTest/MARSTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MARSTest/MARSTest.cs index 69265c4e75..1213c5bfa4 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MARSTest/MARSTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MARSTest/MARSTest.cs @@ -591,7 +591,7 @@ public static void MARSMultiDataReaderErrTest() { using (SqlDataReader reader1 = command.ExecuteReader()) { - DataTestUtility.AssertThrowsWrapper(() => + DataTestUtility.AssertThrows(() => { SqlDataReader reader2 = command.ExecuteReader(); }, openReaderExistsMessage); @@ -611,7 +611,7 @@ public static void MARSMultiDataReaderErrTest() { using (SqlDataReader reader1 = command1.ExecuteReader()) { - DataTestUtility.AssertThrowsWrapper(() => + DataTestUtility.AssertThrows(() => { SqlDataReader reader2 = command2.ExecuteReader(); }, openReaderExistsMessage); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParallelTransactionsTest/ParallelTransactionsTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParallelTransactionsTest/ParallelTransactionsTest.cs index efc99ea757..73fbd8bdc6 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParallelTransactionsTest/ParallelTransactionsTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParallelTransactionsTest/ParallelTransactionsTest.cs @@ -20,7 +20,7 @@ public static void BasicParallelTest_shouldThrowsUnsupported() try { tempTableName = CreateTempTable(connectionString); - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( actionThatFails: () => { BasicParallelTest(connectionString, tempTableName); }, exceptionMessage: expectedErrorMessage); } @@ -77,7 +77,7 @@ public static void MultipleExecutesInSameTransactionTest_shouldThrowsUnsupported try { tempTableName = CreateTempTable(connectionString); - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( actionThatFails: () => { MultipleExecutesInSameTransactionTest(connectionString, tempTableName); }, exceptionMessage: expectedErrorMessage); } @@ -157,5 +157,3 @@ private static void DropTempTable(string connectionString, string tempTableName) } } } - - diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs index a4cd63b0c1..d53209e912 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs @@ -42,14 +42,14 @@ public static void CodeCoverageSqlClient() { string failValue; - DataTestUtility.AssertThrowsWrapper(() => failValue = opc[0].ParameterName, "Invalid index 0 for this SqlParameterCollection with Count=0."); + DataTestUtility.AssertThrows(() => failValue = opc[0].ParameterName, "Invalid index 0 for this SqlParameterCollection with Count=0."); - DataTestUtility.AssertThrowsWrapper(() => failValue = opc["@p1"].ParameterName, "A SqlParameter with ParameterName '@p1' is not contained by this SqlParameterCollection."); + DataTestUtility.AssertThrows(() => failValue = opc["@p1"].ParameterName, "A SqlParameter with ParameterName '@p1' is not contained by this SqlParameterCollection."); - DataTestUtility.AssertThrowsWrapper(() => opc["@p1"] = null, "A SqlParameter with ParameterName '@p1' is not contained by this SqlParameterCollection."); + DataTestUtility.AssertThrows(() => opc["@p1"] = null, "A SqlParameter with ParameterName '@p1' is not contained by this SqlParameterCollection."); } - DataTestUtility.AssertThrowsWrapper(() => opc.Add(null), "The SqlParameterCollection only accepts non-null SqlParameter type objects."); + DataTestUtility.AssertThrows(() => opc.Add(null), "The SqlParameterCollection only accepts non-null SqlParameter type objects."); opc.Add((object)new SqlParameter()); IEnumerator enm = opc.GetEnumerator(); @@ -70,11 +70,11 @@ public static void CodeCoverageSqlClient() SqlParameter p = opc[0]; - DataTestUtility.AssertThrowsWrapper(() => opc.Add((object)p), "The SqlParameter is already contained by another SqlParameterCollection."); + DataTestUtility.AssertThrows(() => opc.Add((object)p), "The SqlParameter is already contained by another SqlParameterCollection."); - DataTestUtility.AssertThrowsWrapper(() => new SqlCommand().Parameters.Add(p), "The SqlParameter is already contained by another SqlParameterCollection."); + DataTestUtility.AssertThrows(() => new SqlCommand().Parameters.Add(p), "The SqlParameter is already contained by another SqlParameterCollection."); - DataTestUtility.AssertThrowsWrapper(() => opc.Remove(null), "The SqlParameterCollection only accepts non-null SqlParameter type objects."); + DataTestUtility.AssertThrows(() => opc.Remove(null), "The SqlParameterCollection only accepts non-null SqlParameter type objects."); string pname = p.ParameterName; p.ParameterName = pname; @@ -106,13 +106,13 @@ public static void CodeCoverageSqlClient() new SqlCommand().Parameters.CopyTo(new object[0], 0); Assert.False(new SqlCommand().Parameters.GetEnumerator().MoveNext(), "FAILED: Expected MoveNext to be false"); - DataTestUtility.AssertThrowsWrapper(() => new SqlCommand().Parameters.Add(0), "The SqlParameterCollection only accepts non-null Microsoft.Data.SqlClient.SqlParameter type objects, not System.Int32 objects."); + DataTestUtility.AssertThrows(() => new SqlCommand().Parameters.Add(0), "The SqlParameterCollection only accepts non-null Microsoft.Data.SqlClient.SqlParameter type objects, not System.Int32 objects."); - DataTestUtility.AssertThrowsWrapper(() => new SqlCommand().Parameters.Insert(0, 0), "The SqlParameterCollection only accepts non-null Microsoft.Data.SqlClient.SqlParameter type objects, not System.Int32 objects."); + DataTestUtility.AssertThrows(() => new SqlCommand().Parameters.Insert(0, 0), "The SqlParameterCollection only accepts non-null Microsoft.Data.SqlClient.SqlParameter type objects, not System.Int32 objects."); - DataTestUtility.AssertThrowsWrapper(() => new SqlCommand().Parameters.Remove(0), "The SqlParameterCollection only accepts non-null Microsoft.Data.SqlClient.SqlParameter type objects, not System.Int32 objects."); + DataTestUtility.AssertThrows(() => new SqlCommand().Parameters.Remove(0), "The SqlParameterCollection only accepts non-null Microsoft.Data.SqlClient.SqlParameter type objects, not System.Int32 objects."); - DataTestUtility.AssertThrowsWrapper(() => new SqlCommand().Parameters.Remove(new SqlParameter()), "Attempted to remove an SqlParameter that is not contained by this SqlParameterCollection."); + DataTestUtility.AssertThrows(() => new SqlCommand().Parameters.Remove(new SqlParameter()), "Attempted to remove an SqlParameter that is not contained by this SqlParameterCollection."); } // TODO Synapse: Parse error at line: 1, column: 12: Incorrect syntax near 'IF'. diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderCancelAsync.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderCancelAsync.cs index 3ae79dbe31..3fb3d051a1 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderCancelAsync.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderCancelAsync.cs @@ -19,7 +19,7 @@ public static void Test(string srcConstr, string dstConstr, string dstTable) cts = new CancellationTokenSource(); cts.Cancel(); Task t = TestAsync(srcConstr, dstConstr, dstTable, cts.Token); - DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + DataTestUtility.AssertThrowsInner(() => t.Wait()); Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status); } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseAsync.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseAsync.cs index fd6062659a..ede16437d3 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseAsync.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseAsync.cs @@ -14,7 +14,7 @@ public class CopyAllFromReaderConnectionClosedAsync public static void Test(string srcConstr, string dstConstr, string dstTable) { Task t = TestAsync(srcConstr, dstConstr, dstTable); - DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + DataTestUtility.AssertThrowsInner(() => t.Wait()); Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status); } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseOnEventAsync.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseOnEventAsync.cs index 1afd2d93d0..3d832925a6 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseOnEventAsync.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseOnEventAsync.cs @@ -4,6 +4,7 @@ using System; using System.Data.Common; +using System.IO; namespace Microsoft.Data.SqlClient.ManualTesting.Tests { @@ -49,7 +50,7 @@ public static void Test(string srcConstr, string dstConstr, string dstTable) // Check that the copying fails string message = string.Format(SystemDataResourceManager.Instance.ADP_OpenConnectionRequired, "WriteToServer", SystemDataResourceManager.Instance.ADP_ConnectionStateMsg_Closed); - DataTestUtility.AssertThrowsWrapper(() => bulkcopy.WriteToServerAsync(reader).Wait(5000), innerExceptionMessage: message); + DataTestUtility.AssertThrowsInnerWithAlternate(() => bulkcopy.WriteToServerAsync(reader).Wait(5000), innerExceptionMessage: message); } } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEvent1.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEvent1.cs index e89f2f83a3..8bc72435d0 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEvent1.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEvent1.cs @@ -66,7 +66,7 @@ public static void Test(string srcConstr, string dstConstr, string dstTable) ColumnMappings.Add("ShipName", "shipname"); bulkcopy.NotifyAfter = 3; - DataTestUtility.AssertThrowsWrapper(() => bulkcopy.WriteToServer(reader)); + DataTestUtility.AssertThrows(() => bulkcopy.WriteToServer(reader)); bulkcopy.SqlRowsCopied -= new SqlRowsCopiedEventHandler(OnRowCopied); bulkcopy.Close(); } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetColumn.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetColumn.cs index d8fe8f66da..e4df366137 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetColumn.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetColumn.cs @@ -38,7 +38,7 @@ public static void Test(string srcConstr, string dstConstr, string dstTable) string errorMsg = SystemDataResourceManager.Instance.SQL_BulkLoadNonMatchingColumnName; errorMsg = string.Format(errorMsg, "col2"); - DataTestUtility.AssertThrowsWrapper(() => bulkcopy.WriteToServer(reader), exceptionMessage: errorMsg); + DataTestUtility.AssertThrows(() => bulkcopy.WriteToServer(reader), exceptionMessage: errorMsg); } } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetColumns.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetColumns.cs index 2696770f69..5fb47f44c1 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetColumns.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetColumns.cs @@ -38,7 +38,7 @@ public static void Test(string srcConstr, string dstConstr, string dstTable) string errorMsg = SystemDataResourceManager.Instance.SQL_BulkLoadNonMatchingColumnName; errorMsg = string.Format(errorMsg, "col3,col4"); - DataTestUtility.AssertThrowsWrapper(() => bulkcopy.WriteToServer(reader), exceptionMessage: errorMsg); + DataTestUtility.AssertThrows(() => bulkcopy.WriteToServer(reader), exceptionMessage: errorMsg); } } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintDuplicateColumn.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintDuplicateColumn.cs index 9e535ccae1..ebed5e9918 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintDuplicateColumn.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintDuplicateColumn.cs @@ -45,7 +45,7 @@ public static void Test(string connStr, string dstTable) string expectedErrorMsg = string.Format( SystemDataResourceManager.Instance.SQL_BulkLoadOrderHintDuplicateColumn, destColumn); - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => bulkcopy.ColumnOrderHints.Add(destColumn, SortOrder.Ascending), exceptionMessage: expectedErrorMsg); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintMissingTargetColumn.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintMissingTargetColumn.cs index 46a7f39eee..cc486e9e4e 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintMissingTargetColumn.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintMissingTargetColumn.cs @@ -44,7 +44,7 @@ public static void Test(string connStr, string dstTable) string expectedErrorMsg = string.Format( SystemDataResourceManager.Instance.SQL_BulkLoadOrderHintInvalidColumn, nonexistentColumn); - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => bulkcopy.WriteToServer(reader), exceptionMessage: expectedErrorMsg); @@ -56,7 +56,7 @@ public static void Test(string connStr, string dstTable) expectedErrorMsg = string.Format( SystemDataResourceManager.Instance.SQL_BulkLoadOrderHintInvalidColumn, sourceColumn); - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => bulkcopy.WriteToServer(reader), exceptionMessage: expectedErrorMsg); } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction.cs index e7632044b0..0738f32010 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction.cs @@ -34,7 +34,7 @@ public static void Test(string srcConstr, string dstConstr, string dstTable) SqlTransaction myTrans = dstConn.BeginTransaction(); try { - DataTestUtility.AssertThrowsWrapper(() => bulkcopy.WriteToServer(reader)); + DataTestUtility.AssertThrows(() => bulkcopy.WriteToServer(reader)); } finally { diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction1.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction1.cs index 1f6ba5e823..930e1ac6f5 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction1.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction1.cs @@ -37,7 +37,7 @@ public static void Test(string srcConstr, string dstConstr, string dstTable) try { - DataTestUtility.AssertThrowsWrapper(() => bulkcopy.WriteToServer(reader)); + DataTestUtility.AssertThrows(() => bulkcopy.WriteToServer(reader)); } finally { diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction3.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction3.cs index 8e53989ed5..4b65f2a5d2 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction3.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction3.cs @@ -37,13 +37,13 @@ public static void Test(string srcConstr, string dstConstr, string dstTable) bulkcopy.DestinationTableName = dstTable; string exceptionMsg = SystemDataResourceManager.Instance.ADP_TransactionConnectionMismatch; - DataTestUtility.AssertThrowsWrapper(() => bulkcopy.WriteToServer(reader), exceptionMessage: exceptionMsg); + DataTestUtility.AssertThrows(() => bulkcopy.WriteToServer(reader), exceptionMessage: exceptionMsg); SqlCommand myCmd = dstConn.CreateCommand(); myCmd.CommandText = "select * from " + dstTable; myCmd.Transaction = myTrans; - DataTestUtility.AssertThrowsWrapper(() => myCmd.ExecuteReader(), exceptionMessage: exceptionMsg); + DataTestUtility.AssertThrows(() => myCmd.ExecuteReader(), exceptionMessage: exceptionMsg); } } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction4.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction4.cs index c8028ca5c5..40b2d2c251 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction4.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction4.cs @@ -31,7 +31,7 @@ public static void Test(string srcConstr, string dstConstr, string dstTable) // Start a local transaction on the wrong connection. SqlTransaction myTrans = conn3.BeginTransaction(); string errorMsg = SystemDataResourceManager.Instance.SQL_BulkLoadConflictingTransactionOption; - DataTestUtility.AssertThrowsWrapper(() => new SqlBulkCopy(dstConn, SqlBulkCopyOptions.UseInternalTransaction, myTrans), exceptionMessage: errorMsg); + DataTestUtility.AssertThrows(() => new SqlBulkCopy(dstConn, SqlBulkCopyOptions.UseInternalTransaction, myTrans), exceptionMessage: errorMsg); } } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/TransactionTestAsync.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/TransactionTestAsync.cs index ac28a9d883..729dac74a9 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/TransactionTestAsync.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/TransactionTestAsync.cs @@ -14,7 +14,7 @@ public class TransactionTestAsync public static void Test(string srcConstr, string dstConstr, string dstTable) { Task t = TestAsync(srcConstr, dstConstr, dstTable); - DataTestUtility.AssertThrowsWrapper(() => t.Wait()); + DataTestUtility.AssertThrowsInner(() => t.Wait()); Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status); } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlCommand/SqlCommandCancelTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlCommand/SqlCommandCancelTest.cs index 97c225c9ca..552fd4cea5 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlCommand/SqlCommandCancelTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlCommand/SqlCommandCancelTest.cs @@ -65,7 +65,7 @@ private static void PlainCancel(string connString) using (SqlDataReader reader = cmd.ExecuteReader()) { cmd.Cancel(); - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => { do @@ -88,7 +88,7 @@ private static void PlainCancelAsync(string connString) { conn.Open(); Task readerTask = cmd.ExecuteReaderAsync(); - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => { readerTask.Wait(2000); @@ -214,7 +214,7 @@ private static void CancelFollowedByTransaction(string constr) private static void CancelFollowedByAlert(string constr) { var alertName = "myAlert" + Guid.NewGuid().ToString(); - // Since Alert conditions are randomly generated, + // Since Alert conditions are randomly generated, // we will retry on unexpected error messages to avoid collision in pipelines. var n = new Random().Next(1, 100); bool retry = true; diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlNotificationTest/SqlNotificationTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlNotificationTest/SqlNotificationTest.cs index 98fa8997de..e4bd1133ac 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlNotificationTest/SqlNotificationTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlNotificationTest/SqlNotificationTest.cs @@ -71,7 +71,7 @@ public void Test_DoubleStart_DifferentConnStr() try { - DataTestUtility.AssertThrowsWrapper(() => SqlDependency.Start(cb.ToString())); + DataTestUtility.AssertThrows(() => SqlDependency.Start(cb.ToString())); } finally { @@ -116,7 +116,7 @@ public void Test_SingleDependency_NoStart() Console.WriteLine("4 Notification callback. Type={0}, Info={1}, Source={2}", args.Type, args.Info, args.Source); }; - DataTestUtility.AssertThrowsWrapper(() => cmd.ExecuteReader()); + DataTestUtility.AssertThrows(() => cmd.ExecuteReader()); } } @@ -138,7 +138,7 @@ public void Test_SingleDependency_Stopped() Console.WriteLine("5 Notification callback. Type={0}, Info={1}, Source={2}", args.Type, args.Info, args.Source); }; - DataTestUtility.AssertThrowsWrapper(() => cmd.ExecuteReader()); + DataTestUtility.AssertThrows(() => cmd.ExecuteReader()); } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.cs index 1a97d6df31..0adff2c8ae 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.cs @@ -339,13 +339,13 @@ private void ExceptionTest() string executeCommandWithoutTransactionMessage = SystemDataResourceManager.Instance.ADP_TransactionRequired("ExecuteNonQuery"); string transactionConflictErrorMessage = SystemDataResourceManager.Instance.ADP_TransactionConnectionMismatch; string parallelTransactionErrorMessage = SystemDataResourceManager.Instance.ADP_ParallelTransactionsNotSupported("SqlConnection"); - DataTestUtility.AssertThrowsWrapper(() => + DataTestUtility.AssertThrows(() => { SqlCommand command = new SqlCommand("sql", connection); command.ExecuteNonQuery(); }, executeCommandWithoutTransactionMessage); - DataTestUtility.AssertThrowsWrapper(() => + DataTestUtility.AssertThrows(() => { using (SqlConnection con1 = new SqlConnection(_connectionString)) { @@ -357,32 +357,32 @@ private void ExceptionTest() } }, transactionConflictErrorMessage); - DataTestUtility.AssertThrowsWrapper(() => + DataTestUtility.AssertThrows(() => { connection.BeginTransaction(null); }, parallelTransactionErrorMessage); - DataTestUtility.AssertThrowsWrapper(() => + DataTestUtility.AssertThrows(() => { connection.BeginTransaction(""); }, parallelTransactionErrorMessage); - DataTestUtility.AssertThrowsWrapper(() => + DataTestUtility.AssertThrows(() => { tx.Rollback(null); }, invalidSaveStateMessage); - DataTestUtility.AssertThrowsWrapper(() => + DataTestUtility.AssertThrows(() => { tx.Rollback(""); }, invalidSaveStateMessage); - DataTestUtility.AssertThrowsWrapper(() => + DataTestUtility.AssertThrows(() => { tx.Save(null); }, invalidSaveStateMessage); - DataTestUtility.AssertThrowsWrapper(() => + DataTestUtility.AssertThrows(() => { tx.Save(""); }, invalidSaveStateMessage); @@ -456,7 +456,7 @@ private void ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWa SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadCommitted); command2.Transaction = tx2; - DataTestUtility.AssertThrowsWrapper(() => command2.ExecuteReader(), SystemDataResourceManager.Instance.SQL_Timeout_Execution as string); + DataTestUtility.AssertThrows(() => command2.ExecuteReader(), SystemDataResourceManager.Instance.SQL_Timeout_Execution as string); tx2.Rollback(); connection2.Close(); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest2.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest2.cs index 79f38262cc..1dae314730 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest2.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest2.cs @@ -75,7 +75,7 @@ public void UDTParams_Binary() value[7] = 0; p.Value = new SqlBinary(value); - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => cmd.ExecuteReader(), "Error converting data type varbinary to Point."); } @@ -110,7 +110,7 @@ public void UDTParams_Invalid2() p.Value = addr; pName.Value = addr; - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => cmd.ExecuteReader(), "Failed to convert parameter value from a Address to a String."); } @@ -134,7 +134,7 @@ public void UDTParams_Invalid() p.UdtTypeName = "UdtTestDb.dbo.Point"; p.Value = 32; - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => cmd.ExecuteReader(), "Specified type is not registered on the target server. System.Int32"); } @@ -221,7 +221,7 @@ public void UDTParams_NullInput() string errorMsg = "Procedure or function '" + spInsertCustomerNoBrackets + "' expects parameter '@addr', which was not supplied."; - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => cmd.ExecuteNonQuery(), errorMsg); } @@ -317,7 +317,7 @@ public void UDTFields_WrongType() reader.Read(); // retrieve the UDT as a string - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => reader.GetString(1), "Unable to cast object of type 'System.Byte[]' to type 'System.String'."); } @@ -584,12 +584,12 @@ Func create string udtError = SystemDataResourceManager.Instance.SQLUDT_MaxByteSizeValue; string errorMessage = (new ArgumentOutOfRangeException("MaxByteSize", 8001, udtError)).Message; - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => create(SqlUserDefinedAggregateAttribute.MaxByteSizeValue + 1), errorMessage); errorMessage = (new ArgumentOutOfRangeException("MaxByteSize", -2, udtError)).Message; - DataTestUtility.AssertThrowsWrapper( + DataTestUtility.AssertThrows( () => create(-2), errorMessage); } @@ -702,4 +702,3 @@ public void UDTParams_DeriveParameters_CheckAutoFixOverride() } } } -