+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Globalization;
-using System.Threading;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class CultureReplacer : IDisposable
- {
- private const string _defaultCultureName = "en-GB";
- private const string _defaultUICultureName = "en-US";
- private static readonly CultureInfo _defaultCulture = new CultureInfo(_defaultCultureName);
- private readonly CultureInfo _originalCulture;
- private readonly CultureInfo _originalUICulture;
- private readonly long _threadId;
-
- // Culture => Formatting of dates/times/money/etc, defaults to en-GB because en-US is the same as InvariantCulture
- // We want to be able to find issues where the InvariantCulture is used, but a specific culture should be.
- //
- // UICulture => Language
- public CultureReplacer(string culture = _defaultCultureName, string uiCulture = _defaultUICultureName)
- : this(new CultureInfo(culture), new CultureInfo(uiCulture))
- {
- }
-
- public CultureReplacer(CultureInfo culture, CultureInfo uiCulture)
- {
- _originalCulture = CultureInfo.CurrentCulture;
- _originalUICulture = CultureInfo.CurrentUICulture;
- _threadId = Thread.CurrentThread.ManagedThreadId;
- CultureInfo.CurrentCulture = culture;
- CultureInfo.CurrentUICulture = uiCulture;
- }
-
- /// <summary>
- /// The name of the culture that is used as the default value for CultureInfo.DefaultThreadCurrentCulture when CultureReplacer is used.
- /// </summary>
- public static string DefaultCultureName
- {
- get { return _defaultCultureName; }
- }
-
- /// <summary>
- /// The name of the culture that is used as the default value for [Thread.CurrentThread(NET45)/CultureInfo(K10)].CurrentUICulture when CultureReplacer is used.
- /// </summary>
- public static string DefaultUICultureName
- {
- get { return _defaultUICultureName; }
- }
-
- /// <summary>
- /// The culture that is used as the default value for [Thread.CurrentThread(NET45)/CultureInfo(K10)].CurrentCulture when CultureReplacer is used.
- /// </summary>
- public static CultureInfo DefaultCulture
- {
- get { return _defaultCulture; }
- }
-
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- private void Dispose(bool disposing)
- {
- if (disposing)
- {
- Assert.True(Thread.CurrentThread.ManagedThreadId == _threadId,
- "The current thread is not the same as the thread invoking the constructor. This should never happen.");
- CultureInfo.CurrentCulture = _originalCulture;
- CultureInfo.CurrentUICulture = _originalUICulture;
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Reflection;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- // TODO: eventually want: public partial class Assert : Xunit.Assert
- public static class ExceptionAssert
- {
- /// <summary>
- /// Verifies that an exception of the given type (or optionally a derived type) is thrown.
- /// </summary>
- /// <typeparam name="TException">The type of the exception expected to be thrown</typeparam>
- /// <param name="testCode">A delegate to the code to be tested</param>
- /// <returns>The exception that was thrown, when successful</returns>
- public static TException Throws<TException>(Action testCode)
- where TException : Exception
- {
- return VerifyException<TException>(RecordException(testCode));
- }
-
- /// <summary>
- /// Verifies that an exception of the given type is thrown.
- /// Also verifies that the exception message matches.
- /// </summary>
- /// <typeparam name="TException">The type of the exception expected to be thrown</typeparam>
- /// <param name="testCode">A delegate to the code to be tested</param>
- /// <param name="exceptionMessage">The exception message to verify</param>
- /// <returns>The exception that was thrown, when successful</returns>
- public static TException Throws<TException>(Action testCode, string exceptionMessage)
- where TException : Exception
- {
- var ex = Throws<TException>(testCode);
- VerifyExceptionMessage(ex, exceptionMessage);
- return ex;
- }
-
- /// <summary>
- /// Verifies that an exception of the given type is thrown.
- /// Also verifies that the exception message matches.
- /// </summary>
- /// <typeparam name="TException">The type of the exception expected to be thrown</typeparam>
- /// <param name="testCode">A delegate to the code to be tested</param>
- /// <param name="exceptionMessage">The exception message to verify</param>
- /// <returns>The exception that was thrown, when successful</returns>
- public static async Task<TException> ThrowsAsync<TException>(Func<Task> testCode, string exceptionMessage)
- where TException : Exception
- {
- // The 'testCode' Task might execute asynchronously in a different thread making it hard to enforce the thread culture.
- // The correct way to verify exception messages in such a scenario would be to run the task synchronously inside of a
- // culture enforced block.
- var ex = await Assert.ThrowsAsync<TException>(testCode);
- VerifyExceptionMessage(ex, exceptionMessage);
- return ex;
- }
-
- /// <summary>
- /// Verifies that an exception of the given type is thrown.
- /// Also verified that the exception message matches.
- /// </summary>
- /// <typeparam name="TException">The type of the exception expected to be thrown</typeparam>
- /// <param name="testCode">A delegate to the code to be tested</param>
- /// <param name="exceptionMessage">The exception message to verify</param>
- /// <returns>The exception that was thrown, when successful</returns>
- public static TException Throws<TException>(Func<object> testCode, string exceptionMessage)
- where TException : Exception
- {
- return Throws<TException>(() => { testCode(); }, exceptionMessage);
- }
-
- /// <summary>
- /// Verifies that the code throws an <see cref="ArgumentException"/>.
- /// </summary>
- /// <param name="testCode">A delegate to the code to be tested</param>
- /// <param name="paramName">The name of the parameter that should throw the exception</param>
- /// <param name="exceptionMessage">The exception message to verify</param>
- /// <returns>The exception that was thrown, when successful</returns>
- public static ArgumentException ThrowsArgument(Action testCode, string paramName, string exceptionMessage)
- {
- return ThrowsArgumentInternal<ArgumentException>(testCode, paramName, exceptionMessage);
- }
-
- private static TException ThrowsArgumentInternal<TException>(
- Action testCode,
- string paramName,
- string exceptionMessage)
- where TException : ArgumentException
- {
- var ex = Throws<TException>(testCode);
- if (paramName != null)
- {
- Assert.Equal(paramName, ex.ParamName);
- }
- VerifyExceptionMessage(ex, exceptionMessage, partialMatch: true);
- return ex;
- }
-
- /// <summary>
- /// Verifies that the code throws an <see cref="ArgumentException"/>.
- /// </summary>
- /// <param name="testCode">A delegate to the code to be tested</param>
- /// <param name="paramName">The name of the parameter that should throw the exception</param>
- /// <param name="exceptionMessage">The exception message to verify</param>
- /// <returns>The exception that was thrown, when successful</returns>
- public static Task<ArgumentException> ThrowsArgumentAsync(Func<Task> testCode, string paramName, string exceptionMessage)
- {
- return ThrowsArgumentAsyncInternal<ArgumentException>(testCode, paramName, exceptionMessage);
- }
-
- private static async Task<TException> ThrowsArgumentAsyncInternal<TException>(
- Func<Task> testCode,
- string paramName,
- string exceptionMessage)
- where TException : ArgumentException
- {
- var ex = await Assert.ThrowsAsync<TException>(testCode);
- if (paramName != null)
- {
- Assert.Equal(paramName, ex.ParamName);
- }
- VerifyExceptionMessage(ex, exceptionMessage, partialMatch: true);
- return ex;
- }
-
- /// <summary>
- /// Verifies that the code throws an <see cref="ArgumentNullException"/>.
- /// </summary>
- /// <param name="testCode">A delegate to the code to be tested</param>
- /// <param name="paramName">The name of the parameter that should throw the exception</param>
- /// <returns>The exception that was thrown, when successful</returns>
- public static ArgumentNullException ThrowsArgumentNull(Action testCode, string paramName)
- {
- var ex = Throws<ArgumentNullException>(testCode);
- if (paramName != null)
- {
- Assert.Equal(paramName, ex.ParamName);
- }
- return ex;
- }
-
- /// <summary>
- /// Verifies that the code throws an ArgumentException with the expected message that indicates that the value cannot
- /// be null or empty.
- /// </summary>
- /// <param name="testCode">A delegate to the code to be tested</param>
- /// <param name="paramName">The name of the parameter that should throw the exception</param>
- /// <returns>The exception that was thrown, when successful</returns>
- public static ArgumentException ThrowsArgumentNullOrEmpty(Action testCode, string paramName)
- {
- return ThrowsArgumentInternal<ArgumentException>(testCode, paramName, "Value cannot be null or empty.");
- }
-
- /// <summary>
- /// Verifies that the code throws an ArgumentException with the expected message that indicates that the value cannot
- /// be null or empty.
- /// </summary>
- /// <param name="testCode">A delegate to the code to be tested</param>
- /// <param name="paramName">The name of the parameter that should throw the exception</param>
- /// <returns>The exception that was thrown, when successful</returns>
- public static Task<ArgumentException> ThrowsArgumentNullOrEmptyAsync(Func<Task> testCode, string paramName)
- {
- return ThrowsArgumentAsyncInternal<ArgumentException>(testCode, paramName, "Value cannot be null or empty.");
- }
-
- /// <summary>
- /// Verifies that the code throws an ArgumentNullException with the expected message that indicates that the value cannot
- /// be null or empty string.
- /// </summary>
- /// <param name="testCode">A delegate to the code to be tested</param>
- /// <param name="paramName">The name of the parameter that should throw the exception</param>
- /// <returns>The exception that was thrown, when successful</returns>
- public static ArgumentException ThrowsArgumentNullOrEmptyString(Action testCode, string paramName)
- {
- return ThrowsArgumentInternal<ArgumentException>(testCode, paramName, "Value cannot be null or an empty string.");
- }
-
- /// <summary>
- /// Verifies that the code throws an ArgumentNullException with the expected message that indicates that the value cannot
- /// be null or empty string.
- /// </summary>
- /// <param name="testCode">A delegate to the code to be tested</param>
- /// <param name="paramName">The name of the parameter that should throw the exception</param>
- /// <returns>The exception that was thrown, when successful</returns>
- public static Task<ArgumentException> ThrowsArgumentNullOrEmptyStringAsync(Func<Task> testCode, string paramName)
- {
- return ThrowsArgumentAsyncInternal<ArgumentException>(testCode, paramName, "Value cannot be null or an empty string.");
- }
-
- /// <summary>
- /// Verifies that the code throws an ArgumentOutOfRangeException (or optionally any exception which derives from it).
- /// </summary>
- /// <param name="testCode">A delegate to the code to be tested</param>
- /// <param name="paramName">The name of the parameter that should throw the exception</param>
- /// <param name="exceptionMessage">The exception message to verify</param>
- /// <param name="actualValue">The actual value provided</param>
- /// <returns>The exception that was thrown, when successful</returns>
- public static ArgumentOutOfRangeException ThrowsArgumentOutOfRange(Action testCode, string paramName, string exceptionMessage, object actualValue = null)
- {
- var ex = ThrowsArgumentInternal<ArgumentOutOfRangeException>(testCode, paramName, exceptionMessage);
-
- if (paramName != null)
- {
- Assert.Equal(paramName, ex.ParamName);
- }
-
- if (actualValue != null)
- {
- Assert.Equal(actualValue, ex.ActualValue);
- }
-
- return ex;
- }
-
- // We've re-implemented all the xUnit.net Throws code so that we can get this
- // updated implementation of RecordException which silently unwraps any instances
- // of AggregateException. In addition to unwrapping exceptions, this method ensures
- // that tests are executed in with a known set of Culture and UICulture. This prevents
- // tests from failing when executed on a non-English machine.
- private static Exception RecordException(Action testCode)
- {
- try
- {
- using (new CultureReplacer())
- {
- testCode();
- }
- return null;
- }
- catch (Exception exception)
- {
- return UnwrapException(exception);
- }
- }
-
- private static Exception UnwrapException(Exception exception)
- {
- var aggEx = exception as AggregateException;
- return aggEx != null ? aggEx.GetBaseException() : exception;
- }
-
- private static TException VerifyException<TException>(Exception exception)
- {
- var tie = exception as TargetInvocationException;
- if (tie != null)
- {
- exception = tie.InnerException;
- }
- Assert.NotNull(exception);
- return Assert.IsAssignableFrom<TException>(exception);
- }
-
- private static void VerifyExceptionMessage(Exception exception, string expectedMessage, bool partialMatch = false)
- {
- if (expectedMessage != null)
- {
- if (!partialMatch)
- {
- Assert.Equal(expectedMessage, exception.Message);
- }
- else
- {
- Assert.Contains(expectedMessage, exception.Message);
- }
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public static class FlakyOn
- {
- public const string All = "All";
-
- public static class Helix
- {
- public const string All = QueuePrefix + "All";
-
- public const string Fedora28Amd64 = QueuePrefix + HelixQueues.Fedora28Amd64;
- public const string Fedora27Amd64 = QueuePrefix + HelixQueues.Fedora27Amd64;
- public const string Redhat7Amd64 = QueuePrefix + HelixQueues.Redhat7Amd64;
- public const string Debian9Amd64 = QueuePrefix + HelixQueues.Debian9Amd64;
- public const string Debian8Amd64 = QueuePrefix + HelixQueues.Debian8Amd64;
- public const string Centos7Amd64 = QueuePrefix + HelixQueues.Centos7Amd64;
- public const string Ubuntu1604Amd64 = QueuePrefix + HelixQueues.Ubuntu1604Amd64;
- public const string Ubuntu1810Amd64 = QueuePrefix + HelixQueues.Ubuntu1810Amd64;
- public const string macOS1012Amd64 = QueuePrefix + HelixQueues.macOS1012Amd64;
- public const string Windows10Amd64 = QueuePrefix + HelixQueues.Windows10Amd64;
-
- private const string Prefix = "Helix:";
- private const string QueuePrefix = Prefix + "Queue:";
- }
-
- public static class AzP
- {
- public const string All = Prefix + "All";
- public const string Windows = OsPrefix + "Windows_NT";
- public const string macOS = OsPrefix + "Darwin";
- public const string Linux = OsPrefix + "Linux";
-
- private const string Prefix = "AzP:";
- private const string OsPrefix = Prefix + "OS:";
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-namespace Microsoft.AspNetCore.Testing
-{
- public static class HelixQueues
- {
- public const string Fedora28Amd64 = "Fedora.28." + Amd64Suffix;
- public const string Fedora27Amd64 = "Fedora.27." + Amd64Suffix;
- public const string Redhat7Amd64 = "Redhat.7." + Amd64Suffix;
- public const string Debian9Amd64 = "Debian.9." + Amd64Suffix;
- public const string Debian8Amd64 = "Debian.8." + Amd64Suffix;
- public const string Centos7Amd64 = "Centos.7." + Amd64Suffix;
- public const string Ubuntu1604Amd64 = "Ubuntu.1604." + Amd64Suffix;
- public const string Ubuntu1810Amd64 = "Ubuntu.1810." + Amd64Suffix;
- public const string macOS1012Amd64 = "OSX.1012." + Amd64Suffix;
- public const string Windows10Amd64 = "Windows.10.Amd64.ClientRS4.VS2017.Open"; // Doesn't have the default suffix!
-
- private const string Amd64Suffix = "Amd64.Open";
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Globalization;
-using System.IO;
-using System.Net;
-using System.Net.Http;
-using System.Net.Security;
-using System.Net.Sockets;
-using System.Runtime.InteropServices;
-using System.Security.Authentication;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Lightweight version of HttpClient implemented using Socket and SslStream.
- /// </summary>
- public static class HttpClientSlim
- {
- public static async Task<string> GetStringAsync(string requestUri, bool validateCertificate = true)
- => await GetStringAsync(new Uri(requestUri), validateCertificate).ConfigureAwait(false);
-
- public static async Task<string> GetStringAsync(Uri requestUri, bool validateCertificate = true)
- {
- return await RetryRequest(async () =>
- {
- using (var stream = await GetStream(requestUri, validateCertificate).ConfigureAwait(false))
- {
- using (var writer = new StreamWriter(stream, Encoding.ASCII, bufferSize: 1024, leaveOpen: true))
- {
- await writer.WriteAsync($"GET {requestUri.PathAndQuery} HTTP/1.0\r\n").ConfigureAwait(false);
- await writer.WriteAsync($"Host: {GetHost(requestUri)}\r\n").ConfigureAwait(false);
- await writer.WriteAsync("\r\n").ConfigureAwait(false);
- }
-
- return await ReadResponse(stream).ConfigureAwait(false);
- }
- });
- }
-
- internal static string GetHost(Uri requestUri)
- {
- var authority = requestUri.Authority;
- if (requestUri.HostNameType == UriHostNameType.IPv6)
- {
- // Make sure there's no % scope id. https://github.com/aspnet/KestrelHttpServer/issues/2637
- var address = IPAddress.Parse(requestUri.Host);
- address = new IPAddress(address.GetAddressBytes()); // Drop scope Id.
- if (requestUri.IsDefaultPort)
- {
- authority = $"[{address}]";
- }
- else
- {
- authority = $"[{address}]:{requestUri.Port.ToString(CultureInfo.InvariantCulture)}";
- }
- }
- return authority;
- }
-
- public static async Task<string> PostAsync(string requestUri, HttpContent content, bool validateCertificate = true)
- => await PostAsync(new Uri(requestUri), content, validateCertificate).ConfigureAwait(false);
-
- public static async Task<string> PostAsync(Uri requestUri, HttpContent content, bool validateCertificate = true)
- {
- return await RetryRequest(async () =>
- {
- using (var stream = await GetStream(requestUri, validateCertificate))
- {
- using (var writer = new StreamWriter(stream, Encoding.ASCII, bufferSize: 1024, leaveOpen: true))
- {
- await writer.WriteAsync($"POST {requestUri.PathAndQuery} HTTP/1.0\r\n").ConfigureAwait(false);
- await writer.WriteAsync($"Host: {requestUri.Authority}\r\n").ConfigureAwait(false);
- await writer.WriteAsync($"Content-Type: {content.Headers.ContentType}\r\n").ConfigureAwait(false);
- await writer.WriteAsync($"Content-Length: {content.Headers.ContentLength}\r\n").ConfigureAwait(false);
- await writer.WriteAsync("\r\n").ConfigureAwait(false);
- }
-
- await content.CopyToAsync(stream).ConfigureAwait(false);
-
- return await ReadResponse(stream).ConfigureAwait(false);
- }
- });
- }
-
- private static async Task<string> ReadResponse(Stream stream)
- {
- using (var reader = new StreamReader(stream, Encoding.ASCII, detectEncodingFromByteOrderMarks: true,
- bufferSize: 1024, leaveOpen: true))
- {
- var response = await reader.ReadToEndAsync().ConfigureAwait(false);
-
- var status = GetStatus(response);
- new HttpResponseMessage(status).EnsureSuccessStatusCode();
-
- var body = response.Substring(response.IndexOf("\r\n\r\n") + 4);
- return body;
- }
- }
-
- private static async Task<string> RetryRequest(Func<Task<string>> retryBlock)
- {
- var retryCount = 1;
- if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- {
- retryCount = 3;
- }
-
- for (var retry = 0; retry < retryCount; retry++)
- {
- try
- {
- return await retryBlock().ConfigureAwait(false);
- }
- catch (InvalidDataException)
- {
- if (retry == retryCount - 1)
- {
- throw;
- }
- }
- }
-
- // This will never be hit.
- throw new NotSupportedException();
- }
-
- private static HttpStatusCode GetStatus(string response)
- {
- var statusStart = response.IndexOf(' ') + 1;
- var statusEnd = response.IndexOf(' ', statusStart) - 1;
- var statusLength = statusEnd - statusStart + 1;
-
- if (statusLength < 1)
- {
- throw new InvalidDataException($"No StatusCode found in '{response}'");
- }
-
- return (HttpStatusCode)int.Parse(response.Substring(statusStart, statusLength));
- }
-
- private static async Task<Stream> GetStream(Uri requestUri, bool validateCertificate)
- {
- var socket = await GetSocket(requestUri);
- var stream = new NetworkStream(socket, ownsSocket: true);
-
- if (requestUri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
- {
- var sslStream = new SslStream(stream, leaveInnerStreamOpen: false, userCertificateValidationCallback:
- validateCertificate ? null : (RemoteCertificateValidationCallback)((a, b, c, d) => true));
-
- await sslStream.AuthenticateAsClientAsync(requestUri.Host, clientCertificates: null,
- enabledSslProtocols: SslProtocols.Tls11 | SslProtocols.Tls12,
- checkCertificateRevocation: validateCertificate).ConfigureAwait(false);
- return sslStream;
- }
- else
- {
- return stream;
- }
- }
-
- public static async Task<Socket> GetSocket(Uri requestUri)
- {
- var tcs = new TaskCompletionSource<Socket>();
-
- var socketArgs = new SocketAsyncEventArgs();
- socketArgs.RemoteEndPoint = new DnsEndPoint(requestUri.DnsSafeHost, requestUri.Port);
- socketArgs.Completed += (s, e) => tcs.TrySetResult(e.ConnectSocket);
-
- // Must use static ConnectAsync(), since instance Connect() does not support DNS names on OSX/Linux.
- if (Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, socketArgs))
- {
- await tcs.Task.ConfigureAwait(false);
- }
-
- var socket = socketArgs.ConnectSocket;
-
- if (socket == null)
- {
- throw new SocketException((int)socketArgs.SocketError);
- }
- else
- {
- return socket;
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Defines a lifecycle for attributes or classes that want to know about tests starting
- /// or ending. Implement this on a test class, or attribute at the method/class/assembly level.
- /// </summary>
- /// <remarks>
- /// Requires defining <see cref="AspNetTestFramework"/> as the test framework.
- /// </remarks>
- public interface ITestMethodLifecycle
- {
- Task OnTestStartAsync(TestContext context, CancellationToken cancellationToken);
-
- Task OnTestEndAsync(TestContext context, Exception exception, CancellationToken cancellationToken);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.ComponentModel;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Runs a test multiple times to stress flaky tests that are believed to be fixed.
- /// This can be used on an assembly, class, or method name. Requires using the AspNetCore test framework.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false)]
- public class RepeatAttribute : Attribute
- {
- public RepeatAttribute(int runCount = 10)
- {
- RunCount = runCount;
- }
-
- /// <summary>
- /// The number of times to run a test.
- /// </summary>
- public int RunCount { get; }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System.Threading;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class RepeatContext
- {
- private static AsyncLocal<RepeatContext> _current = new AsyncLocal<RepeatContext>();
-
- public static RepeatContext Current
- {
- get => _current.Value;
- internal set => _current.Value = value;
- }
-
- public RepeatContext(int limit)
- {
- Limit = limit;
- }
-
- public int Limit { get; }
-
- public int CurrentIteration { get; set; }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Globalization;
-using System.Reflection;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Replaces the current culture and UI culture for the test.
- /// </summary>
- [AttributeUsage(AttributeTargets.Method)]
- public class ReplaceCultureAttribute : BeforeAfterTestAttribute
- {
- private const string _defaultCultureName = "en-GB";
- private const string _defaultUICultureName = "en-US";
- private CultureInfo _originalCulture;
- private CultureInfo _originalUICulture;
-
- /// <summary>
- /// Replaces the current culture and UI culture to en-GB and en-US respectively.
- /// </summary>
- public ReplaceCultureAttribute() :
- this(_defaultCultureName, _defaultUICultureName)
- {
- }
-
- /// <summary>
- /// Replaces the current culture and UI culture based on specified values.
- /// </summary>
- public ReplaceCultureAttribute(string currentCulture, string currentUICulture)
- {
- Culture = new CultureInfo(currentCulture);
- UICulture = new CultureInfo(currentUICulture);
- }
-
- /// <summary>
- /// The <see cref="CultureInfo.CurrentCulture"/> for the test. Defaults to en-GB.
- /// </summary>
- /// <remarks>
- /// en-GB is used here as the default because en-US is equivalent to the InvariantCulture. We
- /// want to be able to find bugs where we're accidentally relying on the Invariant instead of the
- /// user's culture.
- /// </remarks>
- public CultureInfo Culture { get; }
-
- /// <summary>
- /// The <see cref="CultureInfo.CurrentUICulture"/> for the test. Defaults to en-US.
- /// </summary>
- public CultureInfo UICulture { get; }
-
- public override void Before(MethodInfo methodUnderTest)
- {
- _originalCulture = CultureInfo.CurrentCulture;
- _originalUICulture = CultureInfo.CurrentUICulture;
-
- CultureInfo.CurrentCulture = Culture;
- CultureInfo.CurrentUICulture = UICulture;
- }
-
- public override void After(MethodInfo methodUnderTest)
- {
- CultureInfo.CurrentCulture = _originalCulture;
- CultureInfo.CurrentUICulture = _originalUICulture;
- }
- }
-}
-
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Used to specify that <see cref="TestFileOutputContext.TestClassName"/> should used the
- /// unqualified class name. This is needed when a fully-qualified class name exceeds
- /// max path for logging.
- /// </summary>
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false)]
- public class ShortClassNameAttribute : Attribute
- {
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Diagnostics;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public static class TaskExtensions
- {
- public static async Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout,
- [CallerFilePath] string filePath = null,
- [CallerLineNumber] int lineNumber = default)
- {
- // Don't create a timer if the task is already completed
- // or the debugger is attached
- if (task.IsCompleted || Debugger.IsAttached)
- {
- return await task;
- }
-
- var cts = new CancellationTokenSource();
- if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
- {
- cts.Cancel();
- return await task;
- }
- else
- {
- throw new TimeoutException(CreateMessage(timeout, filePath, lineNumber));
- }
- }
-
- public static async Task TimeoutAfter(this Task task, TimeSpan timeout,
- [CallerFilePath] string filePath = null,
- [CallerLineNumber] int lineNumber = default)
- {
- // Don't create a timer if the task is already completed
- // or the debugger is attached
- if (task.IsCompleted || Debugger.IsAttached)
- {
- await task;
- return;
- }
-
- var cts = new CancellationTokenSource();
- if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
- {
- cts.Cancel();
- await task;
- }
- else
- {
- throw new TimeoutException(CreateMessage(timeout, filePath, lineNumber));
- }
- }
-
- private static string CreateMessage(TimeSpan timeout, string filePath, int lineNumber)
- => string.IsNullOrEmpty(filePath)
- ? $"The operation timed out after reaching the limit of {timeout.TotalMilliseconds}ms."
- : $"The operation at {filePath}:{lineNumber} timed out after reaching the limit of {timeout.TotalMilliseconds}ms.";
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Reflection;
-using Xunit.Abstractions;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Provides access to contextual information about the running tests. Get access by
- /// implementing <see cref="ITestMethodLifecycle"/>.
- /// </summary>
- /// <remarks>
- /// Requires defining <see cref="AspNetTestFramework"/> as the test framework.
- /// </remarks>
- public sealed class TestContext
- {
- private Lazy<TestFileOutputContext> _files;
-
- public TestContext(
- Type testClass,
- object[] constructorArguments,
- MethodInfo testMethod,
- object[] methodArguments,
- ITestOutputHelper output)
- {
- TestClass = testClass;
- ConstructorArguments = constructorArguments;
- TestMethod = testMethod;
- MethodArguments = methodArguments;
- Output = output;
-
- _files = new Lazy<TestFileOutputContext>(() => new TestFileOutputContext(this));
- }
-
- public Type TestClass { get; }
- public MethodInfo TestMethod { get; }
- public object[] ConstructorArguments { get; }
- public object[] MethodArguments { get; }
- public ITestOutputHelper Output { get; }
- public TestFileOutputContext FileOutput => _files.Value;
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using System.Text;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Provides access to file storage for the running test. Get access by
- /// implementing <see cref="ITestMethodLifecycle"/>, and accessing <see cref="TestContext.FileOutput"/>.
- /// </summary>
- /// <remarks>
- /// Requires defining <see cref="AspNetTestFramework"/> as the test framework.
- /// </remarks>
- public sealed class TestFileOutputContext
- {
- private static char[] InvalidFileChars = new char[]
- {
- '\"', '<', '>', '|', '\0',
- (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
- (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
- (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
- (char)31, ':', '*', '?', '\\', '/', ' ', (char)127
- };
-
- private readonly TestContext _parent;
-
- public TestFileOutputContext(TestContext parent)
- {
- _parent = parent;
-
- TestName = GetTestMethodName(parent.TestMethod, parent.MethodArguments);
- TestClassName = GetTestClassName(parent.TestClass);
-
- AssemblyOutputDirectory = GetAssemblyBaseDirectory(_parent.TestClass.Assembly);
- if (!string.IsNullOrEmpty(AssemblyOutputDirectory))
- {
- TestClassOutputDirectory = Path.Combine(AssemblyOutputDirectory, TestClassName);
- }
- }
-
- public string TestName { get; }
-
- public string TestClassName { get; }
-
- public string AssemblyOutputDirectory { get; }
-
- public string TestClassOutputDirectory { get; }
-
- public string GetUniqueFileName(string prefix, string extension)
- {
- if (prefix == null)
- {
- throw new ArgumentNullException(nameof(prefix));
- }
-
- if (extension != null && !extension.StartsWith(".", StringComparison.Ordinal))
- {
- throw new ArgumentException("The extension must start with '.' if one is provided.", nameof(extension));
- }
-
- var path = Path.Combine(TestClassOutputDirectory, $"{prefix}{extension}");
-
- var i = 1;
- while (File.Exists(path))
- {
- path = Path.Combine(TestClassOutputDirectory, $"{prefix}{i++}{extension}");
- }
-
- return path;
- }
-
- // Gets the output directory without appending the TFM or assembly name.
- public static string GetOutputDirectory(Assembly assembly)
- {
- var attribute = assembly.GetCustomAttributes().OfType<TestOutputDirectoryAttribute>().FirstOrDefault();
- return attribute?.BaseDirectory;
- }
-
- public static string GetAssemblyBaseDirectory(Assembly assembly, string baseDirectory = null)
- {
- var attribute = assembly.GetCustomAttributes().OfType<TestOutputDirectoryAttribute>().FirstOrDefault();
- baseDirectory = baseDirectory ?? attribute?.BaseDirectory;
- if (string.IsNullOrEmpty(baseDirectory))
- {
- return string.Empty;
- }
-
- return Path.Combine(baseDirectory, assembly.GetName().Name, attribute.TargetFramework);
- }
-
- public static bool GetPreserveExistingLogsInOutput(Assembly assembly)
- {
- var attribute = assembly.GetCustomAttributes().OfType<TestOutputDirectoryAttribute>().FirstOrDefault();
- return attribute.PreserveExistingLogsInOutput;
- }
-
- public static string GetTestClassName(Type type)
- {
- var shortNameAttribute =
- type.GetCustomAttribute<ShortClassNameAttribute>() ??
- type.Assembly.GetCustomAttribute<ShortClassNameAttribute>();
- var name = shortNameAttribute == null ? type.FullName : type.Name;
-
- // Try to shorten the class name using the assembly name
- var assemblyName = type.Assembly.GetName().Name;
- if (name.StartsWith(assemblyName + "."))
- {
- name = name.Substring(assemblyName.Length + 1);
- }
-
- return name;
- }
-
- public static string GetTestMethodName(MethodInfo method, object[] arguments)
- {
- var name = arguments.Aggregate(method.Name, (a, b) => $"{a}-{(b ?? "null")}");
- return RemoveIllegalFileChars(name);
- }
-
- public static string RemoveIllegalFileChars(string s)
- {
- var sb = new StringBuilder();
-
- foreach (var c in s)
- {
- if (InvalidFileChars.Contains(c))
- {
- if (sb.Length > 0 && sb[sb.Length - 1] != '_')
- {
- sb.Append('_');
- }
- }
- else
- {
- sb.Append(c);
- }
- }
- return sb.ToString();
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = true)]
- public class TestOutputDirectoryAttribute : Attribute
- {
- public TestOutputDirectoryAttribute(string preserveExistingLogsInOutput, string targetFramework, string baseDirectory = null)
- {
- TargetFramework = targetFramework;
- BaseDirectory = baseDirectory;
- PreserveExistingLogsInOutput = bool.Parse(preserveExistingLogsInOutput);
- }
-
- public string BaseDirectory { get; }
- public string TargetFramework { get; }
- public bool PreserveExistingLogsInOutput { get; }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.IO;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [Obsolete("This API is obsolete and the pattern its usage encouraged should not be used anymore. See https://github.com/dotnet/extensions/issues/1697 for details.")]
- public class TestPathUtilities
- {
- public static string GetRepoRootDirectory()
- {
- return GetSolutionRootDirectory("Extensions");
- }
-
- public static string GetSolutionRootDirectory(string solution)
- {
- var applicationBasePath = AppContext.BaseDirectory;
- var directoryInfo = new DirectoryInfo(applicationBasePath);
-
- do
- {
- var projectFileInfo = new FileInfo(Path.Combine(directoryInfo.FullName, $"{solution}.sln"));
- if (projectFileInfo.Exists)
- {
- return projectFileInfo.DirectoryName;
- }
-
- directoryInfo = directoryInfo.Parent;
- }
- while (directoryInfo.Parent != null);
-
- throw new Exception($"Solution file {solution}.sln could not be found in {applicationBasePath} or its parent directories.");
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Runtime.InteropServices;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public static class TestPlatformHelper
- {
- public static bool IsMono =>
- Type.GetType("Mono.Runtime") != null;
-
- public static bool IsWindows =>
- RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
-
- public static bool IsLinux =>
- RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
-
- public static bool IsMac =>
- RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.Diagnostics.Tracing;
-using System.Linq;
-
-namespace Microsoft.AspNetCore.Testing.Tracing
-{
- public class CollectingEventListener : EventListener
- {
- private ConcurrentQueue<EventWrittenEventArgs> _events = new ConcurrentQueue<EventWrittenEventArgs>();
-
- private object _lock = new object();
-
- private Dictionary<string, EventSource> _existingSources = new Dictionary<string, EventSource>(StringComparer.OrdinalIgnoreCase);
- private HashSet<string> _requestedEventSources = new HashSet<string>();
-
- public void CollectFrom(string eventSourceName)
- {
- lock(_lock)
- {
- // Check if it's already been created
- if(_existingSources.TryGetValue(eventSourceName, out var existingSource))
- {
- // It has, so just enable it now
- CollectFrom(existingSource);
- }
- else
- {
- // It hasn't, so queue this request for when it is created
- _requestedEventSources.Add(eventSourceName);
- }
- }
- }
-
- public void CollectFrom(EventSource eventSource) => EnableEvents(eventSource, EventLevel.Verbose, EventKeywords.All);
-
- public IReadOnlyList<EventWrittenEventArgs> GetEventsWritten() => _events.ToArray();
-
- protected override void OnEventSourceCreated(EventSource eventSource)
- {
- lock (_lock)
- {
- // Add this to the list of existing sources for future CollectEventsFrom requests.
- _existingSources[eventSource.Name] = eventSource;
-
- // Check if we have a pending request to enable it
- if (_requestedEventSources.Contains(eventSource.Name))
- {
- CollectFrom(eventSource);
- }
- }
- }
-
- protected override void OnEventWritten(EventWrittenEventArgs eventData)
- {
- _events.Enqueue(eventData);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.Tracing;
-using System.Linq;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing.Tracing
-{
- public class EventAssert
- {
- private readonly int _expectedId;
- private readonly string _expectedName;
- private readonly EventLevel _expectedLevel;
- private readonly IList<(string name, Action<object> asserter)> _payloadAsserters = new List<(string, Action<object>)>();
-
- public EventAssert(int expectedId, string expectedName, EventLevel expectedLevel)
- {
- _expectedId = expectedId;
- _expectedName = expectedName;
- _expectedLevel = expectedLevel;
- }
-
- public static void Collection(IEnumerable<EventWrittenEventArgs> events, params EventAssert[] asserts)
- {
- Assert.Collection(
- events,
- asserts.Select(a => a.CreateAsserter()).ToArray());
- }
-
- public static EventAssert Event(int id, string name, EventLevel level)
- {
- return new EventAssert(id, name, level);
- }
-
- public EventAssert Payload(string name, object expectedValue) => Payload(name, actualValue => Assert.Equal(expectedValue, actualValue));
-
- public EventAssert Payload(string name, Action<object> asserter)
- {
- _payloadAsserters.Add((name, asserter));
- return this;
- }
-
- private Action<EventWrittenEventArgs> CreateAsserter() => Execute;
-
- private void Execute(EventWrittenEventArgs evt)
- {
- Assert.Equal(_expectedId, evt.EventId);
- Assert.Equal(_expectedName, evt.EventName);
- Assert.Equal(_expectedLevel, evt.Level);
-
- Action<string> CreateNameAsserter((string name, Action<object> asserter) val)
- {
- return actualValue => Assert.Equal(val.name, actualValue);
- }
-
- Assert.Collection(evt.PayloadNames, _payloadAsserters.Select(CreateNameAsserter).ToArray());
- Assert.Collection(evt.Payload, _payloadAsserters.Select(t => t.asserter).ToArray());
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.Tracing;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing.Tracing
-{
- // This collection attribute is what makes the "magic" happen. It forces xunit to run all tests that inherit from this
- // base class sequentially, preventing conflicts (since EventSource/EventListener is a process-global concept).
- [Collection(CollectionName)]
- public abstract class EventSourceTestBase : IDisposable
- {
- public const string CollectionName = "Microsoft.AspNetCore.Testing.Tracing.EventSourceTestCollection";
-
- private readonly CollectingEventListener _listener;
-
- public EventSourceTestBase()
- {
- _listener = new CollectingEventListener();
- }
-
- protected void CollectFrom(string eventSourceName)
- {
- _listener.CollectFrom(eventSourceName);
- }
-
- protected void CollectFrom(EventSource eventSource)
- {
- _listener.CollectFrom(eventSource);
- }
-
- protected IReadOnlyList<EventWrittenEventArgs> GetEvents() => _listener.GetEventsWritten();
-
- public void Dispose()
- {
- _listener.Dispose();
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-namespace Microsoft.AspNetCore.Testing.Tracing
-{
- // This file comes from Microsoft.AspNetCore.Testing and has to be defined in the test assembly.
- // It enables EventSourceTestBase's parallel isolation functionality.
-
- [Xunit.CollectionDefinition(EventSourceTestBase.CollectionName, DisableParallelization = true)]
- public class EventSourceTestCollection
- {
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class AspNetTestAssemblyRunner : XunitTestAssemblyRunner
- {
- private readonly Dictionary<Type, object> _assemblyFixtureMappings = new Dictionary<Type, object>();
-
- public AspNetTestAssemblyRunner(
- ITestAssembly testAssembly,
- IEnumerable<IXunitTestCase> testCases,
- IMessageSink diagnosticMessageSink,
- IMessageSink executionMessageSink,
- ITestFrameworkExecutionOptions executionOptions)
- : base(testAssembly, testCases, diagnosticMessageSink, executionMessageSink, executionOptions)
- {
- }
-
- protected override async Task AfterTestAssemblyStartingAsync()
- {
- await base.AfterTestAssemblyStartingAsync();
-
- // Find all the AssemblyFixtureAttributes on the test assembly
- Aggregator.Run(() =>
- {
- var fixturesAttributes = ((IReflectionAssemblyInfo)TestAssembly.Assembly)
- .Assembly
- .GetCustomAttributes(typeof(AssemblyFixtureAttribute), false)
- .Cast<AssemblyFixtureAttribute>()
- .ToList();
-
- // Instantiate all the fixtures
- foreach (var fixtureAttribute in fixturesAttributes)
- {
- var ctorWithDiagnostics = fixtureAttribute.FixtureType.GetConstructor(new[] { typeof(IMessageSink) });
- if (ctorWithDiagnostics != null)
- {
- _assemblyFixtureMappings[fixtureAttribute.FixtureType] = Activator.CreateInstance(fixtureAttribute.FixtureType, DiagnosticMessageSink);
- }
- else
- {
- _assemblyFixtureMappings[fixtureAttribute.FixtureType] = Activator.CreateInstance(fixtureAttribute.FixtureType);
- }
- }
- });
- }
-
- protected override Task BeforeTestAssemblyFinishedAsync()
- {
- // Dispose fixtures
- foreach (var disposable in _assemblyFixtureMappings.Values.OfType<IDisposable>())
- {
- Aggregator.Run(disposable.Dispose);
- }
-
- return base.BeforeTestAssemblyFinishedAsync();
- }
-
- protected override Task<RunSummary> RunTestCollectionAsync(
- IMessageBus messageBus,
- ITestCollection testCollection,
- IEnumerable<IXunitTestCase> testCases,
- CancellationTokenSource cancellationTokenSource)
- => new AspNetTestCollectionRunner(
- _assemblyFixtureMappings,
- testCollection,
- testCases,
- DiagnosticMessageSink,
- messageBus,
- TestCaseOrderer,
- new ExceptionAggregator(Aggregator),
- cancellationTokenSource).RunAsync();
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Threading;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- internal class AspNetTestCaseRunner : XunitTestCaseRunner
- {
- public AspNetTestCaseRunner(
- IXunitTestCase testCase,
- string displayName,
- string skipReason,
- object[] constructorArguments,
- object[] testMethodArguments,
- IMessageBus messageBus,
- ExceptionAggregator aggregator,
- CancellationTokenSource cancellationTokenSource)
- : base(testCase, displayName, skipReason, constructorArguments, testMethodArguments, messageBus, aggregator, cancellationTokenSource)
- {
- }
-
- protected override XunitTestRunner CreateTestRunner(ITest test, IMessageBus messageBus, Type testClass, object[] constructorArguments, MethodInfo testMethod, object[] testMethodArguments, string skipReason, IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource)
- {
- return new AspNetTestRunner(test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, skipReason, beforeAfterAttributes, aggregator, cancellationTokenSource);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- internal class AspNetTestClassRunner : XunitTestClassRunner
- {
- public AspNetTestClassRunner(
- ITestClass testClass,
- IReflectionTypeInfo @class,
- IEnumerable<IXunitTestCase> testCases,
- IMessageSink diagnosticMessageSink,
- IMessageBus messageBus,
- ITestCaseOrderer testCaseOrderer,
- ExceptionAggregator aggregator,
- CancellationTokenSource cancellationTokenSource,
- IDictionary<Type, object> collectionFixtureMappings)
- : base(testClass, @class, testCases, diagnosticMessageSink, messageBus, testCaseOrderer, aggregator, cancellationTokenSource, collectionFixtureMappings)
- {
- }
-
- protected override Task<RunSummary> RunTestMethodAsync(ITestMethod testMethod, IReflectionMethodInfo method, IEnumerable<IXunitTestCase> testCases, object[] constructorArguments)
- {
- var runner = new AspNetTestMethodRunner(
- testMethod,
- Class,
- method,
- testCases,
- DiagnosticMessageSink,
- MessageBus,
- new ExceptionAggregator(Aggregator),
- CancellationTokenSource,
- constructorArguments);
- return runner.RunAsync();
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class AspNetTestCollectionRunner : XunitTestCollectionRunner
- {
- private readonly IDictionary<Type, object> _assemblyFixtureMappings;
- private readonly IMessageSink _diagnosticMessageSink;
-
- public AspNetTestCollectionRunner(
- Dictionary<Type, object> assemblyFixtureMappings,
- ITestCollection testCollection,
- IEnumerable<IXunitTestCase> testCases,
- IMessageSink diagnosticMessageSink,
- IMessageBus messageBus,
- ITestCaseOrderer testCaseOrderer,
- ExceptionAggregator aggregator,
- CancellationTokenSource cancellationTokenSource)
- : base(testCollection, testCases, diagnosticMessageSink, messageBus, testCaseOrderer, aggregator, cancellationTokenSource)
- {
- _assemblyFixtureMappings = assemblyFixtureMappings;
- _diagnosticMessageSink = diagnosticMessageSink;
- }
-
- protected override async Task AfterTestCollectionStartingAsync()
- {
- await base.AfterTestCollectionStartingAsync();
-
- // note: We pass the assembly fixtures into the runner as ICollectionFixture<> - this seems to work OK without any
- // drawbacks. It's reasonable that we could add IAssemblyFixture<> and related plumbing if it ever became required.
- //
- // The reason for assembly fixture is when we want to start/stop something as the project scope - tests can only be
- // in one test collection at a time.
- foreach (var mapping in _assemblyFixtureMappings)
- {
- CollectionFixtureMappings.Add(mapping.Key, mapping.Value);
- }
- }
-
- protected override Task BeforeTestCollectionFinishedAsync()
- {
- // We need to remove the assembly fixtures so they won't get disposed.
- foreach (var mapping in _assemblyFixtureMappings)
- {
- CollectionFixtureMappings.Remove(mapping.Key);
- }
-
- return base.BeforeTestCollectionFinishedAsync();
- }
-
- protected override Task<RunSummary> RunTestClassAsync(ITestClass testClass, IReflectionTypeInfo @class, IEnumerable<IXunitTestCase> testCases)
- {
- var runner = new AspNetTestClassRunner(
- testClass,
- @class,
- testCases,
- DiagnosticMessageSink,
- MessageBus,
- TestCaseOrderer,
- new ExceptionAggregator(Aggregator),
- CancellationTokenSource,
- CollectionFixtureMappings);
- return runner.RunAsync();
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System.Reflection;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class AspNetTestFramework : XunitTestFramework
- {
- public AspNetTestFramework(IMessageSink messageSink)
- : base(messageSink)
- {
- }
-
- protected override ITestFrameworkExecutor CreateExecutor(AssemblyName assemblyName)
- => new AspNetTestFrameworkExecutor(assemblyName, SourceInformationProvider, DiagnosticMessageSink);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System.Collections.Generic;
-using System.Reflection;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class AspNetTestFrameworkExecutor : XunitTestFrameworkExecutor
- {
- public AspNetTestFrameworkExecutor(AssemblyName assemblyName, ISourceInformationProvider sourceInformationProvider, IMessageSink diagnosticMessageSink)
- : base(assemblyName, sourceInformationProvider, diagnosticMessageSink)
- {
- }
-
- protected override async void RunTestCases(IEnumerable<IXunitTestCase> testCases, IMessageSink executionMessageSink, ITestFrameworkExecutionOptions executionOptions)
- {
- using (var assemblyRunner = new AspNetTestAssemblyRunner(TestAssembly, testCases, DiagnosticMessageSink, executionMessageSink, executionOptions))
- {
- await assemblyRunner.RunAsync();
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- internal class AspNetTestInvoker : XunitTestInvoker
- {
- public AspNetTestInvoker(
- ITest test,
- IMessageBus messageBus,
- Type testClass,
- object[] constructorArguments,
- MethodInfo testMethod,
- object[] testMethodArguments,
- IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes,
- ExceptionAggregator aggregator,
- CancellationTokenSource cancellationTokenSource)
- : base(test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, beforeAfterAttributes, aggregator, cancellationTokenSource)
- {
- }
-
- protected override async Task<decimal> InvokeTestMethodAsync(object testClassInstance)
- {
- var output = new TestOutputHelper();
- output.Initialize(MessageBus, Test);
-
- var context = new TestContext(TestClass, ConstructorArguments, TestMethod, TestMethodArguments, output);
- var lifecycleHooks = GetLifecycleHooks(testClassInstance, TestClass, TestMethod);
-
- await Aggregator.RunAsync(async () =>
- {
- foreach (var lifecycleHook in lifecycleHooks)
- {
- await lifecycleHook.OnTestStartAsync(context, CancellationTokenSource.Token);
- }
- });
-
- var time = await base.InvokeTestMethodAsync(testClassInstance);
-
- await Aggregator.RunAsync(async () =>
- {
- var exception = Aggregator.HasExceptions ? Aggregator.ToException() : null;
- foreach (var lifecycleHook in lifecycleHooks)
- {
- await lifecycleHook.OnTestEndAsync(context, exception, CancellationTokenSource.Token);
- }
- });
-
- return time;
- }
-
- private static IEnumerable<ITestMethodLifecycle> GetLifecycleHooks(object testClassInstance, Type testClass, MethodInfo testMethod)
- {
- foreach (var attribute in testMethod.GetCustomAttributes(inherit: true).OfType<ITestMethodLifecycle>())
- {
- yield return attribute;
- }
-
- if (testClassInstance is ITestMethodLifecycle instance)
- {
- yield return instance;
- }
-
- foreach (var attribute in testClass.GetCustomAttributes(inherit: true).OfType<ITestMethodLifecycle>())
- {
- yield return attribute;
- }
-
- foreach (var attribute in testClass.Assembly.GetCustomAttributes(inherit: true).OfType<ITestMethodLifecycle>())
- {
- yield return attribute;
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing.xunit;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- internal class AspNetTestMethodRunner : XunitTestMethodRunner
- {
- private readonly object[] _constructorArguments;
- private readonly IMessageSink _diagnosticMessageSink;
-
- public AspNetTestMethodRunner(
- ITestMethod testMethod,
- IReflectionTypeInfo @class,
- IReflectionMethodInfo method,
- IEnumerable<IXunitTestCase> testCases,
- IMessageSink diagnosticMessageSink,
- IMessageBus messageBus,
- ExceptionAggregator aggregator,
- CancellationTokenSource cancellationTokenSource,
- object[] constructorArguments)
- : base(testMethod, @class, method, testCases, diagnosticMessageSink, messageBus, aggregator, cancellationTokenSource, constructorArguments)
- {
- _diagnosticMessageSink = diagnosticMessageSink;
- _constructorArguments = constructorArguments;
- }
-
- protected override Task<RunSummary> RunTestCaseAsync(IXunitTestCase testCase)
- {
- if (testCase.GetType() == typeof(XunitTestCase))
- {
- // If we get here this is a 'regular' test case, not something that represents a skipped test.
- //
- // We can take control of it's invocation thusly.
- var runner = new AspNetTestCaseRunner(
- testCase,
- testCase.DisplayName,
- testCase.SkipReason,
- _constructorArguments,
- testCase.TestMethodArguments,
- MessageBus,
- new ExceptionAggregator(Aggregator),
- CancellationTokenSource);
- return runner.RunAsync();
- }
-
- if (testCase.GetType() == typeof(XunitTheoryTestCase))
- {
- // If we get here this is a 'regular' theory test case, not something that represents a skipped test.
- //
- // We can take control of it's invocation thusly.
- var runner = new AspNetTheoryTestCaseRunner(
- testCase,
- testCase.DisplayName,
- testCase.SkipReason,
- _constructorArguments,
- _diagnosticMessageSink,
- MessageBus,
- new ExceptionAggregator(Aggregator),
- CancellationTokenSource);
- return runner.RunAsync();
- }
-
- return base.RunTestCaseAsync(testCase);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- internal class AspNetTestRunner : XunitTestRunner
- {
- public AspNetTestRunner(
- ITest test,
- IMessageBus messageBus,
- Type testClass,
- object[] constructorArguments,
- MethodInfo testMethod,
- object[] testMethodArguments,
- string skipReason,
- IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes,
- ExceptionAggregator aggregator,
- CancellationTokenSource cancellationTokenSource)
- : base(test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, skipReason, beforeAfterAttributes, aggregator, cancellationTokenSource)
- {
- }
-
- protected override async Task<decimal> InvokeTestMethodAsync(ExceptionAggregator aggregator)
- {
- var repeatAttribute = GetRepeatAttribute(TestMethod);
- if (repeatAttribute == null)
- {
- return await InvokeTestMethodCoreAsync(aggregator);
- }
-
- var repeatContext = new RepeatContext(repeatAttribute.RunCount);
- RepeatContext.Current = repeatContext;
-
- var timeTaken = 0.0M;
- for (repeatContext.CurrentIteration = 0; repeatContext.CurrentIteration < repeatContext.Limit; repeatContext.CurrentIteration++)
- {
- timeTaken = await InvokeTestMethodCoreAsync(aggregator);
- if (aggregator.HasExceptions)
- {
- return timeTaken;
- }
- }
-
- return timeTaken;
- }
-
- private Task<decimal> InvokeTestMethodCoreAsync(ExceptionAggregator aggregator)
- {
- var invoker = new AspNetTestInvoker(Test, MessageBus, TestClass, ConstructorArguments, TestMethod, TestMethodArguments, BeforeAfterAttributes, aggregator, CancellationTokenSource);
- return invoker.RunAsync();
- }
-
- private RepeatAttribute GetRepeatAttribute(MethodInfo methodInfo)
- {
- var attributeCandidate = methodInfo.GetCustomAttribute<RepeatAttribute>();
- if (attributeCandidate != null)
- {
- return attributeCandidate;
- }
-
- attributeCandidate = methodInfo.DeclaringType.GetCustomAttribute<RepeatAttribute>();
- if (attributeCandidate != null)
- {
- return attributeCandidate;
- }
-
- return methodInfo.DeclaringType.Assembly.GetCustomAttribute<RepeatAttribute>();
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Threading;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing.xunit
-{
- internal class AspNetTheoryTestCaseRunner : XunitTheoryTestCaseRunner
- {
- public AspNetTheoryTestCaseRunner(
- IXunitTestCase testCase,
- string displayName,
- string skipReason,
- object[] constructorArguments,
- IMessageSink diagnosticMessageSink,
- IMessageBus messageBus,
- ExceptionAggregator aggregator,
- CancellationTokenSource cancellationTokenSource)
- : base(testCase, displayName, skipReason, constructorArguments, diagnosticMessageSink, messageBus, aggregator, cancellationTokenSource)
- {
- }
-
- protected override XunitTestRunner CreateTestRunner(ITest test, IMessageBus messageBus, Type testClass, object[] constructorArguments, MethodInfo testMethod, object[] testMethodArguments, string skipReason, IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource)
- {
- return new AspNetTestRunner(test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, skipReason, beforeAfterAttributes, aggregator, cancellationTokenSource);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
- public class AssemblyFixtureAttribute : Attribute
- {
- public AssemblyFixtureAttribute(Type fixtureType)
- {
- FixtureType = fixtureType;
- }
-
- public Type FixtureType { get; private set; }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using Xunit;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
- [XunitTestCaseDiscoverer("Microsoft.AspNetCore.Testing." + nameof(ConditionalFactDiscoverer), "Microsoft.AspNetCore.Testing")]
- public class ConditionalFactAttribute : FactAttribute
- {
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-// Do not change this namespace without changing the usage in ConditionalFactAttribute
-namespace Microsoft.AspNetCore.Testing
-{
- internal class ConditionalFactDiscoverer : FactDiscoverer
- {
- private readonly IMessageSink _diagnosticMessageSink;
-
- public ConditionalFactDiscoverer(IMessageSink diagnosticMessageSink)
- : base(diagnosticMessageSink)
- {
- _diagnosticMessageSink = diagnosticMessageSink;
- }
-
- protected override IXunitTestCase CreateTestCase(ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod, IAttributeInfo factAttribute)
- {
- var skipReason = testMethod.EvaluateSkipConditions();
- return skipReason != null
- ? new SkippedTestCase(skipReason, _diagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), TestMethodDisplayOptions.None, testMethod)
- : base.CreateTestCase(discoveryOptions, testMethod, factAttribute);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using Xunit;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
- [XunitTestCaseDiscoverer("Microsoft.AspNetCore.Testing." + nameof(ConditionalTheoryDiscoverer), "Microsoft.AspNetCore.Testing")]
- public class ConditionalTheoryAttribute : TheoryAttribute
- {
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-// Do not change this namespace without changing the usage in ConditionalTheoryAttribute
-namespace Microsoft.AspNetCore.Testing
-{
- internal class ConditionalTheoryDiscoverer : TheoryDiscoverer
- {
- public ConditionalTheoryDiscoverer(IMessageSink diagnosticMessageSink)
- : base(diagnosticMessageSink)
- {
- }
-
- private sealed class OptionsWithPreEnumerationEnabled : ITestFrameworkDiscoveryOptions
- {
- private const string PreEnumerateTheories = "xunit.discovery.PreEnumerateTheories";
-
- private readonly ITestFrameworkDiscoveryOptions _original;
-
- public OptionsWithPreEnumerationEnabled(ITestFrameworkDiscoveryOptions original)
- => _original = original;
-
- public TValue GetValue<TValue>(string name)
- => (name == PreEnumerateTheories) ? (TValue)(object)true : _original.GetValue<TValue>(name);
-
- public void SetValue<TValue>(string name, TValue value)
- => _original.SetValue(name, value);
- }
-
- public override IEnumerable<IXunitTestCase> Discover(ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod, IAttributeInfo theoryAttribute)
- => base.Discover(new OptionsWithPreEnumerationEnabled(discoveryOptions), testMethod, theoryAttribute);
-
- protected override IEnumerable<IXunitTestCase> CreateTestCasesForTheory(ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod, IAttributeInfo theoryAttribute)
- {
- var skipReason = testMethod.EvaluateSkipConditions();
- return skipReason != null
- ? new[] { new SkippedTestCase(skipReason, DiagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), TestMethodDisplayOptions.None, testMethod) }
- : base.CreateTestCasesForTheory(discoveryOptions, testMethod, theoryAttribute);
- }
-
- protected override IEnumerable<IXunitTestCase> CreateTestCasesForDataRow(ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod, IAttributeInfo theoryAttribute, object[] dataRow)
- {
- var skipReason = testMethod.EvaluateSkipConditions();
- if (skipReason == null && dataRow?.Length > 0)
- {
- var obj = dataRow[0];
- if (obj != null)
- {
- var type = obj.GetType();
- var property = type.GetProperty("Skip");
- if (property != null && property.PropertyType.Equals(typeof(string)))
- {
- skipReason = property.GetValue(obj) as string;
- }
- }
- }
-
- return skipReason != null ?
- base.CreateTestCasesForSkippedDataRow(discoveryOptions, testMethod, theoryAttribute, dataRow, skipReason)
- : base.CreateTestCasesForDataRow(discoveryOptions, testMethod, theoryAttribute, dataRow);
- }
-
- protected override IEnumerable<IXunitTestCase> CreateTestCasesForSkippedDataRow(
- ITestFrameworkDiscoveryOptions discoveryOptions,
- ITestMethod testMethod,
- IAttributeInfo theoryAttribute,
- object[] dataRow,
- string skipReason)
- {
- return new[]
- {
- new WORKAROUND_SkippedDataRowTestCase(DiagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), discoveryOptions.MethodDisplayOptionsOrDefault(), testMethod, skipReason, dataRow),
- };
- }
-
- [Obsolete]
- protected override IXunitTestCase CreateTestCaseForSkippedDataRow(ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod, IAttributeInfo theoryAttribute, object[] dataRow, string skipReason)
- {
- return new WORKAROUND_SkippedDataRowTestCase(DiagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), discoveryOptions.MethodDisplayOptionsOrDefault(), testMethod, skipReason, dataRow);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.IO;
-using System.Linq;
-using System.Runtime.InteropServices;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
- public sealed class DockerOnlyAttribute : Attribute, ITestCondition
- {
- public string SkipReason { get; } = "This test can only run in a Docker container.";
-
- public bool IsMet
- {
- get
- {
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- {
- // we currently don't have a good way to detect if running in a Windows container
- return false;
- }
-
- const string procFile = "/proc/1/cgroup";
- if (!File.Exists(procFile))
- {
- return false;
- }
-
- var lines = File.ReadAllLines(procFile);
- // typically the last line in the file is "1:name=openrc:/docker"
- return lines.Reverse().Any(l => l.EndsWith("name=openrc:/docker", StringComparison.Ordinal));
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Linq;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Skips a test when the value of an environment variable matches any of the supplied values.
- /// </summary>
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
- public class EnvironmentVariableSkipConditionAttribute : Attribute, ITestCondition
- {
- private readonly string _variableName;
- private readonly string[] _values;
- private string _currentValue;
- private readonly IEnvironmentVariable _environmentVariable;
-
- /// <summary>
- /// Creates a new instance of <see cref="EnvironmentVariableSkipConditionAttribute"/>.
- /// </summary>
- /// <param name="variableName">Name of the environment variable.</param>
- /// <param name="values">Value(s) of the environment variable to match for the test to be skipped</param>
- public EnvironmentVariableSkipConditionAttribute(string variableName, params string[] values)
- : this(new EnvironmentVariable(), variableName, values)
- {
- }
-
- // To enable unit testing
- internal EnvironmentVariableSkipConditionAttribute(
- IEnvironmentVariable environmentVariable,
- string variableName,
- params string[] values)
- {
- if (environmentVariable == null)
- {
- throw new ArgumentNullException(nameof(environmentVariable));
- }
- if (variableName == null)
- {
- throw new ArgumentNullException(nameof(variableName));
- }
- if (values == null)
- {
- throw new ArgumentNullException(nameof(values));
- }
-
- _variableName = variableName;
- _values = values;
- _environmentVariable = environmentVariable;
- }
-
- /// <summary>
- /// Runs the test only if the value of the variable matches any of the supplied values. Default is <c>True</c>.
- /// </summary>
- public bool RunOnMatch { get; set; } = true;
-
- public bool IsMet
- {
- get
- {
- _currentValue = _environmentVariable.Get(_variableName);
- var hasMatched = _values.Any(value => string.Compare(value, _currentValue, ignoreCase: true) == 0);
-
- if (RunOnMatch)
- {
- return hasMatched;
- }
- else
- {
- return !hasMatched;
- }
- }
- }
-
- public string SkipReason
- {
- get
- {
- var value = _currentValue == null ? "(null)" : _currentValue;
- return $"Test skipped on environment variable with name '{_variableName}' and value '{value}' " +
- $"for the '{nameof(RunOnMatch)}' value of '{RunOnMatch}'.";
- }
- }
-
- private struct EnvironmentVariable : IEnvironmentVariable
- {
- public string Get(string name)
- {
- return Environment.GetEnvironmentVariable(name);
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Marks a test as "Flaky" so that the build will sequester it and ignore failures.
- /// </summary>
- /// <remarks>
- /// <para>
- /// This attribute works by applying xUnit.net "Traits" based on the criteria specified in the attribute
- /// properties. Once these traits are applied, build scripts can include/exclude tests based on them.
- /// </para>
- /// <para>
- /// All flakiness-related traits start with <c>Flaky:</c> and are grouped first by the process running the tests: Azure Pipelines (AzP) or Helix.
- /// Then there is a segment specifying the "selector" which indicates where the test is flaky. Finally a segment specifying the value of that selector.
- /// The value of these traits is always either "true" or the trait is not present. We encode the entire selector in the name of the trait because xUnit.net only
- /// provides "==" and "!=" operators for traits, there is no way to check if a trait "contains" or "does not contain" a value. VSTest does support "contains" checks
- /// but does not appear to support "does not contain" checks. Using this pattern means we can use simple "==" and "!=" checks to either only run flaky tests, or exclude
- /// flaky tests.
- /// </para>
- /// </remarks>
- /// <example>
- /// <code>
- /// [Fact]
- /// [Flaky("...", HelixQueues.Fedora28Amd64, AzurePipelines.macOS)]
- /// public void FlakyTest()
- /// {
- /// // Flakiness
- /// }
- /// </code>
- ///
- /// <para>
- /// The above example generates the following facets:
- /// </para>
- ///
- /// <list type="bullet">
- /// <item>
- /// <description><c>Flaky:Helix:Queue:Fedora.28.Amd64.Open</c> = <c>true</c></description>
- /// </item>
- /// <item>
- /// <description><c>Flaky:AzP:OS:Darwin</c> = <c>true</c></description>
- /// </item>
- /// </list>
- ///
- /// <para>
- /// Given the above attribute, the Azure Pipelines macOS run can easily filter this test out by passing <c>-notrait "Flaky:AzP:OS:all=true" -notrait "Flaky:AzP:OS:Darwin=true"</c>
- /// to <c>xunit.console.exe</c>. Similarly, it can run only flaky tests using <c>-trait "Flaky:AzP:OS:all=true" -trait "Flaky:AzP:OS:Darwin=true"</c>
- /// </para>
- /// </example>
- [TraitDiscoverer("Microsoft.AspNetCore.Testing." + nameof(FlakyTraitDiscoverer), "Microsoft.AspNetCore.Testing")]
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
- public sealed class FlakyAttribute : Attribute, ITraitAttribute
- {
- /// <summary>
- /// Gets a URL to a GitHub issue tracking this flaky test.
- /// </summary>
- public string GitHubIssueUrl { get; }
-
- public IReadOnlyList<string> Filters { get; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="FlakyAttribute"/> class with the specified <see cref="GitHubIssueUrl"/> and a list of <see cref="Filters"/>. If no
- /// filters are provided, the test is considered flaky in all environments.
- /// </summary>
- /// <remarks>
- /// At least one filter is required.
- /// </remarks>
- /// <param name="gitHubIssueUrl">The URL to a GitHub issue tracking this flaky test.</param>
- /// <param name="firstFilter">The first filter that indicates where the test is flaky. Use a value from <see cref="FlakyOn"/>.</param>
- /// <param name="additionalFilters">A list of additional filters that define where this test is flaky. Use values in <see cref="FlakyOn"/>.</param>
- public FlakyAttribute(string gitHubIssueUrl, string firstFilter, params string[] additionalFilters)
- {
- if (string.IsNullOrEmpty(gitHubIssueUrl))
- {
- throw new ArgumentNullException(nameof(gitHubIssueUrl));
- }
-
- if (string.IsNullOrEmpty(firstFilter))
- {
- throw new ArgumentNullException(nameof(firstFilter));
- }
-
- GitHubIssueUrl = gitHubIssueUrl;
- var filters = new List<string>();
- filters.Add(firstFilter);
- filters.AddRange(additionalFilters);
- Filters = filters;
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-// Do not change this namespace without changing the usage in FlakyAttribute
-namespace Microsoft.AspNetCore.Testing
-{
- public class FlakyTraitDiscoverer : ITraitDiscoverer
- {
- public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
- {
- if (traitAttribute is ReflectionAttributeInfo attribute && attribute.Attribute is FlakyAttribute flakyAttribute)
- {
- return GetTraitsCore(flakyAttribute);
- }
- else
- {
- throw new InvalidOperationException("The 'Flaky' attribute is only supported via reflection.");
- }
- }
-
- private IEnumerable<KeyValuePair<string, string>> GetTraitsCore(FlakyAttribute attribute)
- {
- if (attribute.Filters.Count > 0)
- {
- foreach (var filter in attribute.Filters)
- {
- yield return new KeyValuePair<string, string>($"Flaky:{filter}", "true");
- }
- }
- else
- {
- yield return new KeyValuePair<string, string>($"Flaky:All", "true");
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
- public class FrameworkSkipConditionAttribute : Attribute, ITestCondition
- {
- private readonly RuntimeFrameworks _excludedFrameworks;
-
- public FrameworkSkipConditionAttribute(RuntimeFrameworks excludedFrameworks)
- {
- _excludedFrameworks = excludedFrameworks;
- }
-
- public bool IsMet
- {
- get
- {
- return CanRunOnThisFramework(_excludedFrameworks);
- }
- }
-
- public string SkipReason { get; set; } = "Test cannot run on this runtime framework.";
-
- private static bool CanRunOnThisFramework(RuntimeFrameworks excludedFrameworks)
- {
- if (excludedFrameworks == RuntimeFrameworks.None)
- {
- return true;
- }
-
-#if NETFRAMEWORK
- if (excludedFrameworks.HasFlag(RuntimeFrameworks.Mono) &&
- TestPlatformHelper.IsMono)
- {
- return false;
- }
-
- if (excludedFrameworks.HasFlag(RuntimeFrameworks.CLR))
- {
- return false;
- }
-#elif NETSTANDARD2_0 || NETCOREAPP
- if (excludedFrameworks.HasFlag(RuntimeFrameworks.CoreCLR))
- {
- return false;
- }
-#else
-#error Target frameworks need to be updated.
-#endif
- return true;
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-namespace Microsoft.AspNetCore.Testing
-{
- internal interface IEnvironmentVariable
- {
- string Get(string name);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-namespace Microsoft.AspNetCore.Testing
-{
- public interface ITestCondition
- {
- bool IsMet { get; }
-
- string SkipReason { get; }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Runtime.InteropServices;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Skips a test if the OS is the given type (Windows) and the OS version is greater than specified.
- /// E.g. Specifying Window 8 skips on Win 10, but not on Linux. Combine with OSSkipConditionAttribute as needed.
- /// </summary>
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
- public class MaximumOSVersionAttribute : Attribute, ITestCondition
- {
- private readonly OperatingSystems _targetOS;
- private readonly Version _maxVersion;
- private readonly OperatingSystems _currentOS;
- private readonly Version _currentVersion;
- private readonly bool _skip;
-
- public MaximumOSVersionAttribute(OperatingSystems operatingSystem, string maxVersion) :
- this(operatingSystem, Version.Parse(maxVersion), GetCurrentOS(), GetCurrentOSVersion())
- {
- }
-
- // to enable unit testing
- internal MaximumOSVersionAttribute(OperatingSystems targetOS, Version maxVersion, OperatingSystems currentOS, Version currentVersion)
- {
- if (targetOS != OperatingSystems.Windows)
- {
- throw new NotImplementedException("Max version support is only implemented for Windows.");
- }
- _targetOS = targetOS;
- _maxVersion = maxVersion;
- _currentOS = currentOS;
- // We drop the 4th field because it is not significant and it messes up the comparisons.
- _currentVersion = new Version(currentVersion.Major, currentVersion.Minor,
- // Major and Minor are required by the parser, but if Build isn't specified then it returns -1
- // which the constructor rejects.
- currentVersion.Build == -1 ? 0 : currentVersion.Build);
-
- // Do not skip other OS's, Use OSSkipConditionAttribute or a separate MaximumOsVersionAttribute for that.
- _skip = _targetOS == _currentOS && _maxVersion < _currentVersion;
- SkipReason = $"This test requires {_targetOS} {_maxVersion} or earlier.";
- }
-
- // Since a test would be executed only if 'IsMet' is true, return false if we want to skip
- public bool IsMet => !_skip;
-
- public string SkipReason { get; set; }
-
- private static OperatingSystems GetCurrentOS()
- {
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- {
- return OperatingSystems.Windows;
- }
- else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
- {
- return OperatingSystems.Linux;
- }
- else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- {
- return OperatingSystems.MacOSX;
- }
- throw new PlatformNotSupportedException();
- }
-
- static private Version GetCurrentOSVersion()
- {
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- {
- return Environment.OSVersion.Version;
- }
- else
- {
- // Not implemented, but this will still be called before the OS check happens so don't throw.
- return new Version(0, 0);
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Runtime.InteropServices;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Skips a test if the OS is the given type (Windows) and the OS version is less than specified.
- /// E.g. Specifying Window 10.0 skips on Win 8, but not on Linux. Combine with OSSkipConditionAttribute as needed.
- /// </summary>
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
- public class MinimumOSVersionAttribute : Attribute, ITestCondition
- {
- private readonly OperatingSystems _targetOS;
- private readonly Version _minVersion;
- private readonly OperatingSystems _currentOS;
- private readonly Version _currentVersion;
- private readonly bool _skip;
-
- public MinimumOSVersionAttribute(OperatingSystems operatingSystem, string minVersion) :
- this(operatingSystem, Version.Parse(minVersion), GetCurrentOS(), GetCurrentOSVersion())
- {
- }
-
- // to enable unit testing
- internal MinimumOSVersionAttribute(OperatingSystems targetOS, Version minVersion, OperatingSystems currentOS, Version currentVersion)
- {
- if (targetOS != OperatingSystems.Windows)
- {
- throw new NotImplementedException("Min version support is only implemented for Windows.");
- }
- _targetOS = targetOS;
- _minVersion = minVersion;
- _currentOS = currentOS;
- _currentVersion = currentVersion;
-
- // Do not skip other OS's, Use OSSkipConditionAttribute or a separate MinimumOSVersionAttribute for that.
- _skip = _targetOS == _currentOS && _minVersion > _currentVersion;
- SkipReason = $"This test requires {_targetOS} {_minVersion} or later.";
- }
-
- // Since a test would be executed only if 'IsMet' is true, return false if we want to skip
- public bool IsMet => !_skip;
-
- public string SkipReason { get; set; }
-
- private static OperatingSystems GetCurrentOS()
- {
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- {
- return OperatingSystems.Windows;
- }
- else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
- {
- return OperatingSystems.Linux;
- }
- else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- {
- return OperatingSystems.MacOSX;
- }
- throw new PlatformNotSupportedException();
- }
-
- static private Version GetCurrentOSVersion()
- {
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- {
- return Environment.OSVersion.Version;
- }
- else
- {
- // Not implemented, but this will still be called before the OS check happens so don't throw.
- return new Version(0, 0);
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Runtime.InteropServices;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
- public class OSSkipConditionAttribute : Attribute, ITestCondition
- {
- private readonly OperatingSystems _excludedOperatingSystem;
- private readonly OperatingSystems _osPlatform;
-
- public OSSkipConditionAttribute(OperatingSystems operatingSystem) :
- this(operatingSystem, GetCurrentOS())
- {
- }
-
- [Obsolete("Use the Minimum/MaximumOSVersionAttribute for version checks.", error: true)]
- public OSSkipConditionAttribute(OperatingSystems operatingSystem, params string[] versions) :
- this(operatingSystem, GetCurrentOS())
- {
- }
-
- // to enable unit testing
- internal OSSkipConditionAttribute(OperatingSystems operatingSystem, OperatingSystems osPlatform)
- {
- _excludedOperatingSystem = operatingSystem;
- _osPlatform = osPlatform;
- }
-
- public bool IsMet
- {
- get
- {
- var skip = (_excludedOperatingSystem & _osPlatform) == _osPlatform;
- // Since a test would be excuted only if 'IsMet' is true, return false if we want to skip
- return !skip;
- }
- }
-
- public string SkipReason { get; set; } = "Test cannot run on this operating system.";
-
- static private OperatingSystems GetCurrentOS()
- {
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- {
- return OperatingSystems.Windows;
- }
- else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
- {
- return OperatingSystems.Linux;
- }
- else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- {
- return OperatingSystems.MacOSX;
- }
- throw new PlatformNotSupportedException();
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [Flags]
- public enum OperatingSystems
- {
- Linux = 1,
- MacOSX = 2,
- Windows = 4,
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [Flags]
- public enum RuntimeFrameworks
- {
- None = 0,
- Mono = 1 << 0,
- CLR = 1 << 1,
- CoreCLR = 1 << 2
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Skip test if running on CI
- /// </summary>
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
- public class SkipOnCIAttribute : Attribute, ITestCondition
- {
- public SkipOnCIAttribute(string issueUrl = "")
- {
- IssueUrl = issueUrl;
- }
-
- public string IssueUrl { get; }
-
- public bool IsMet
- {
- get
- {
- return !OnCI();
- }
- }
-
- public string SkipReason
- {
- get
- {
- return $"This test is skipped on CI";
- }
- }
-
- public static bool OnCI() => OnHelix() || OnAzdo();
- public static bool OnHelix() => !string.IsNullOrEmpty(GetTargetHelixQueue());
- public static string GetTargetHelixQueue() => Environment.GetEnvironmentVariable("helix");
- public static bool OnAzdo() => !string.IsNullOrEmpty(GetIfOnAzdo());
- public static string GetIfOnAzdo() => Environment.GetEnvironmentVariable("AGENT_OS");
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Linq;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// Skip test if running on helix (or a particular helix queue).
- /// </summary>
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
- public class SkipOnHelixAttribute : Attribute, ITestCondition
- {
- public SkipOnHelixAttribute(string issueUrl)
- {
- if (string.IsNullOrEmpty(issueUrl))
- {
- throw new ArgumentException();
- }
- IssueUrl = issueUrl;
- }
-
- public string IssueUrl { get; }
-
- public bool IsMet
- {
- get
- {
- var skip = OnHelix() && (Queues == null || Queues.ToLowerInvariant().Split(';').Contains(GetTargetHelixQueue().ToLowerInvariant()));
- return !skip;
- }
- }
-
- // Queues that should be skipped on, i.e. "Windows.10.Amd64.ClientRS4.VS2017.Open;OSX.1012.Amd64.Open"
- public string Queues { get; set; }
-
- public string SkipReason
- {
- get
- {
- return $"This test is skipped on helix";
- }
- }
-
- public static bool OnHelix() => !string.IsNullOrEmpty(GetTargetHelixQueue());
-
- public static string GetTargetHelixQueue() => Environment.GetEnvironmentVariable("helix");
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class SkippedTestCase : XunitTestCase
- {
- private string _skipReason;
-
- [Obsolete("Called by the de-serializer; should only be called by deriving classes for de-serialization purposes")]
- public SkippedTestCase() : base()
- {
- }
-
- public SkippedTestCase(
- string skipReason,
- IMessageSink diagnosticMessageSink,
- TestMethodDisplay defaultMethodDisplay,
- TestMethodDisplayOptions defaultMethodDisplayOptions,
- ITestMethod testMethod,
- object[] testMethodArguments = null)
- : base(diagnosticMessageSink, defaultMethodDisplay, defaultMethodDisplayOptions, testMethod, testMethodArguments)
- {
- _skipReason = skipReason;
- }
-
- protected override string GetSkipReason(IAttributeInfo factAttribute)
- => _skipReason ?? base.GetSkipReason(factAttribute);
-
- public override void Deserialize(IXunitSerializationInfo data)
- {
- _skipReason = data.GetValue<string>(nameof(_skipReason));
-
- // We need to call base after reading our value, because Deserialize will call
- // into GetSkipReason.
- base.Deserialize(data);
- }
-
- public override void Serialize(IXunitSerializationInfo data)
- {
- base.Serialize(data);
- data.AddValue(nameof(_skipReason), _skipReason);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System.Linq;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public static class TestMethodExtensions
- {
- public static string EvaluateSkipConditions(this ITestMethod testMethod)
- {
- var testClass = testMethod.TestClass.Class;
- var assembly = testMethod.TestClass.TestCollection.TestAssembly.Assembly;
- var conditionAttributes = testMethod.Method
- .GetCustomAttributes(typeof(ITestCondition))
- .Concat(testClass.GetCustomAttributes(typeof(ITestCondition)))
- .Concat(assembly.GetCustomAttributes(typeof(ITestCondition)))
- .OfType<ReflectionAttributeInfo>()
- .Select(attributeInfo => attributeInfo.Attribute);
-
- foreach (ITestCondition condition in conditionAttributes)
- {
- if (!condition.IsMet)
- {
- return condition.SkipReason;
- }
- }
-
- return null;
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.ComponentModel;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- // This is a workaround for https://github.com/xunit/xunit/issues/1782 - as such, this code is a copy-paste
- // from xUnit with the exception of fixing the bug.
- //
- // This will only work with [ConditionalTheory].
- internal class WORKAROUND_SkippedDataRowTestCase : XunitTestCase
- {
- string skipReason;
-
- /// <summary/>
- [EditorBrowsable(EditorBrowsableState.Never)]
- [Obsolete("Called by the de-serializer; should only be called by deriving classes for de-serialization purposes")]
- public WORKAROUND_SkippedDataRowTestCase() { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="XunitSkippedDataRowTestCase"/> class.
- /// </summary>
- /// <param name="diagnosticMessageSink">The message sink used to send diagnostic messages</param>
- /// <param name="defaultMethodDisplay">Default method display to use (when not customized).</param>
- /// <param name="testMethod">The test method this test case belongs to.</param>
- /// <param name="skipReason">The reason that this test case will be skipped</param>
- /// <param name="testMethodArguments">The arguments for the test method.</param>
- [Obsolete("Please call the constructor which takes TestMethodDisplayOptions")]
- public WORKAROUND_SkippedDataRowTestCase(IMessageSink diagnosticMessageSink,
- TestMethodDisplay defaultMethodDisplay,
- ITestMethod testMethod,
- string skipReason,
- object[] testMethodArguments = null)
- : this(diagnosticMessageSink, defaultMethodDisplay, TestMethodDisplayOptions.None, testMethod, skipReason, testMethodArguments) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="XunitSkippedDataRowTestCase"/> class.
- /// </summary>
- /// <param name="diagnosticMessageSink">The message sink used to send diagnostic messages</param>
- /// <param name="defaultMethodDisplay">Default method display to use (when not customized).</param>
- /// <param name="defaultMethodDisplayOptions">Default method display options to use (when not customized).</param>
- /// <param name="testMethod">The test method this test case belongs to.</param>
- /// <param name="skipReason">The reason that this test case will be skipped</param>
- /// <param name="testMethodArguments">The arguments for the test method.</param>
- public WORKAROUND_SkippedDataRowTestCase(IMessageSink diagnosticMessageSink,
- TestMethodDisplay defaultMethodDisplay,
- TestMethodDisplayOptions defaultMethodDisplayOptions,
- ITestMethod testMethod,
- string skipReason,
- object[] testMethodArguments = null)
- : base(diagnosticMessageSink, defaultMethodDisplay, defaultMethodDisplayOptions, testMethod, testMethodArguments)
- {
- this.skipReason = skipReason;
- }
-
- /// <inheritdoc/>
- public override void Deserialize(IXunitSerializationInfo data)
- {
- // SkipReason has to be read before we call base.Deserialize, this is the workaround.
- this.skipReason = data.GetValue<string>("SkipReason");
-
- base.Deserialize(data);
- }
-
- /// <inheritdoc/>
- protected override string GetSkipReason(IAttributeInfo factAttribute)
- {
- return skipReason;
- }
-
- /// <inheritdoc/>
- public override void Serialize(IXunitSerializationInfo data)
- {
- base.Serialize(data);
-
- data.AddValue("SkipReason", skipReason);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-
-namespace Microsoft.AspNetCore.Testing
-{
- /// <summary>
- /// https://en.wikipedia.org/wiki/Windows_10_version_history
- /// </summary>
- public static class WindowsVersions
- {
- public const string Win7 = "6.1";
-
- [Obsolete("Use Win7 instead.", error: true)]
- public const string Win2008R2 = Win7;
-
- public const string Win8 = "6.2";
-
- public const string Win81 = "6.3";
-
- public const string Win10 = "10.0";
-
- /// <summary>
- /// 1803, RS4, 17134
- /// </summary>
- public const string Win10_RS4 = "10.0.17134";
-
- /// <summary>
- /// 1809, RS5, 17763
- /// </summary>
- public const string Win10_RS5 = "10.0.17763";
-
- /// <summary>
- /// 1903, 19H1, 18362
- /// </summary>
- public const string Win10_19H1 = "10.0.18362";
-
- /// <summary>
- /// 1909, 19H2, 18363
- /// </summary>
- public const string Win10_19H2 = "10.0.18363";
-
- /// <summary>
- /// 2004, 20H1, 19033
- /// </summary>
- public const string Win10_20H1 = "10.0.19033";
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Xunit.Abstractions;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class AlphabeticalOrderer : ITestCaseOrderer
- {
- public IEnumerable<TTestCase> OrderTestCases<TTestCase>(IEnumerable<TTestCase> testCases)
- where TTestCase : ITestCase
- {
- var result = testCases.ToList();
- result.Sort((x, y) => StringComparer.OrdinalIgnoreCase.Compare(x.TestMethod.Method.Name, y.TestMethod.Method.Name));
- return result;
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- // We include a collection and assembly fixture to verify that they both still work.
- [Collection("MyCollection")]
- [TestCaseOrderer("Microsoft.AspNetCore.Testing.AlphabeticalOrderer", "Microsoft.AspNetCore.Testing.Tests")]
- public class AssemblyFixtureTest
- {
- public AssemblyFixtureTest(TestAssemblyFixture assemblyFixture, TestCollectionFixture collectionFixture)
- {
- AssemblyFixture = assemblyFixture;
- CollectionFixture = collectionFixture;
- }
-
- public TestAssemblyFixture AssemblyFixture { get; }
- public TestCollectionFixture CollectionFixture { get; }
-
- [Fact]
- public void A()
- {
- Assert.NotNull(AssemblyFixture);
- Assert.Equal(0, AssemblyFixture.Count);
-
- Assert.NotNull(CollectionFixture);
- Assert.Equal(0, CollectionFixture.Count);
-
- AssemblyFixture.Count++;
- CollectionFixture.Count++;
- }
-
- [Fact]
- public void B()
- {
- Assert.Equal(1, AssemblyFixture.Count);
- Assert.Equal(1, CollectionFixture.Count);
- }
- }
-
- [CollectionDefinition("MyCollection", DisableParallelization = true)]
- public class MyCollection : ICollectionFixture<TestCollectionFixture>
- {
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System.Diagnostics.Tracing;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing.Tracing;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing.Tests
-{
- // We are verifying here that when event listener tests are spread among multiple classes, they still
- // work, even when run in parallel. To do that we have a bunch of tests in different classes (since
- // that affects parallelism) and do some Task.Yielding in them.
- public class CollectingEventListenerTests
- {
- public abstract class CollectingTestBase : EventSourceTestBase
- {
- [Fact]
- public async Task CollectingEventListenerTest()
- {
- CollectFrom("Microsoft-AspNetCore-Testing-Test");
-
- await Task.Yield();
- TestEventSource.Log.Test();
- await Task.Yield();
- TestEventSource.Log.TestWithPayload(42, 4.2);
- await Task.Yield();
-
- var events = GetEvents();
- EventAssert.Collection(events,
- EventAssert.Event(1, "Test", EventLevel.Informational),
- EventAssert.Event(2, "TestWithPayload", EventLevel.Verbose)
- .Payload("payload1", 42)
- .Payload("payload2", 4.2));
- }
- }
-
- // These tests are designed to interfere with the collecting ones by running in parallel and writing events
- public abstract class NonCollectingTestBase
- {
- [Fact]
- public async Task CollectingEventListenerTest()
- {
- await Task.Yield();
- TestEventSource.Log.Test();
- await Task.Yield();
- TestEventSource.Log.TestWithPayload(42, 4.2);
- await Task.Yield();
- }
- }
-
- public class CollectingTests
- {
- public class A : CollectingTestBase { }
- public class B : CollectingTestBase { }
- public class C : CollectingTestBase { }
- public class D : CollectingTestBase { }
- public class E : CollectingTestBase { }
- public class F : CollectingTestBase { }
- public class G : CollectingTestBase { }
- }
-
- public class NonCollectingTests
- {
- public class A : NonCollectingTestBase { }
- public class B : NonCollectingTestBase { }
- public class C : NonCollectingTestBase { }
- public class D : NonCollectingTestBase { }
- public class E : NonCollectingTestBase { }
- public class F : NonCollectingTestBase { }
- public class G : NonCollectingTestBase { }
- }
- }
-
- [EventSource(Name = "Microsoft-AspNetCore-Testing-Test")]
- public class TestEventSource : EventSource
- {
- public static readonly TestEventSource Log = new TestEventSource();
-
- private TestEventSource()
- {
- }
-
- [Event(eventId: 1, Level = EventLevel.Informational, Message = "Test")]
- public void Test() => WriteEvent(1);
-
- [Event(eventId: 2, Level = EventLevel.Verbose, Message = "Test")]
- public void TestWithPayload(int payload1, double payload2) => WriteEvent(2, payload1, payload2);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [TestCaseOrderer("Microsoft.AspNetCore.Testing.AlphabeticalOrderer", "Microsoft.AspNetCore.Testing.Tests")]
- public class ConditionalFactTest : IClassFixture<ConditionalFactTest.ConditionalFactAsserter>
- {
- public ConditionalFactTest(ConditionalFactAsserter collector)
- {
- Asserter = collector;
- }
-
- private ConditionalFactAsserter Asserter { get; }
-
- [Fact]
- public void TestAlwaysRun()
- {
- // This is required to ensure that the type at least gets initialized.
- Assert.True(true);
- }
-
- [ConditionalFact(Skip = "Test is always skipped.")]
- public void ConditionalFactSkip()
- {
- Assert.True(false, "This test should always be skipped.");
- }
-
-#if NETCOREAPP
- [ConditionalFact]
- [FrameworkSkipCondition(RuntimeFrameworks.CLR)]
- public void ThisTestMustRunOnCoreCLR()
- {
- Asserter.TestRan = true;
- }
-#elif NETFRAMEWORK
- [ConditionalFact]
- [FrameworkSkipCondition(RuntimeFrameworks.CoreCLR)]
- public void ThisTestMustRunOnCLR()
- {
- Asserter.TestRan = true;
- }
-#else
-#error Target frameworks need to be updated.
-#endif
-
- // Test is named this way to be the lowest test in the alphabet, it relies on test ordering
- [Fact]
- public void ZzzzzzzEnsureThisIsTheLastTest()
- {
- Assert.True(Asserter.TestRan);
- }
-
- public class ConditionalFactAsserter : IDisposable
- {
- public bool TestRan { get; set; }
-
- public void Dispose()
- {
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using Xunit;
-using Xunit.Abstractions;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [TestCaseOrderer("Microsoft.AspNetCore.Testing.AlphabeticalOrderer", "Microsoft.AspNetCore.Testing.Tests")]
- public class ConditionalTheoryTest : IClassFixture<ConditionalTheoryTest.ConditionalTheoryAsserter>
- {
- public ConditionalTheoryTest(ConditionalTheoryAsserter asserter)
- {
- Asserter = asserter;
- }
-
- public ConditionalTheoryAsserter Asserter { get; }
-
- [ConditionalTheory(Skip = "Test is always skipped.")]
- [InlineData(0)]
- public void ConditionalTheorySkip(int arg)
- {
- Assert.True(false, "This test should always be skipped.");
- }
-
- private static int _conditionalTheoryRuns = 0;
-
- [ConditionalTheory]
- [InlineData(0)]
- [InlineData(1)]
- [InlineData(2, Skip = "Skip these data")]
- public void ConditionalTheoryRunOncePerDataLine(int arg)
- {
- _conditionalTheoryRuns++;
- Assert.True(_conditionalTheoryRuns <= 2, $"Theory should run 2 times, but ran {_conditionalTheoryRuns} times.");
- }
-
- [ConditionalTheory, Trait("Color", "Blue")]
- [InlineData(1)]
- public void ConditionalTheoriesShouldPreserveTraits(int arg)
- {
- Assert.True(true);
- }
-
- [ConditionalTheory(Skip = "Skip this")]
- [MemberData(nameof(GetInts))]
- public void ConditionalTheoriesWithSkippedMemberData(int arg)
- {
- Assert.True(false, "This should never run");
- }
-
- private static int _conditionalMemberDataRuns = 0;
-
- [ConditionalTheory]
- [InlineData(4)]
- [MemberData(nameof(GetInts))]
- public void ConditionalTheoriesWithMemberData(int arg)
- {
- _conditionalMemberDataRuns++;
- Assert.True(_conditionalTheoryRuns <= 3, $"Theory should run 2 times, but ran {_conditionalMemberDataRuns} times.");
- }
-
- public static TheoryData<int> GetInts
- => new TheoryData<int> { 0, 1 };
-
- [ConditionalTheory]
- [OSSkipCondition(OperatingSystems.Windows)]
- [OSSkipCondition(OperatingSystems.MacOSX)]
- [OSSkipCondition(OperatingSystems.Linux)]
- [MemberData(nameof(GetActionTestData))]
- public void ConditionalTheoryWithFuncs(Func<int, int> func)
- {
- Assert.True(false, "This should never run");
- }
-
- [Fact]
- public void TestAlwaysRun()
- {
- // This is required to ensure that this type at least gets initialized.
- Assert.True(true);
- }
-
-#if NETCOREAPP
- [ConditionalTheory]
- [FrameworkSkipCondition(RuntimeFrameworks.CLR)]
- [MemberData(nameof(GetInts))]
- public void ThisTestMustRunOnCoreCLR(int value)
- {
- Asserter.TestRan = true;
- }
-#elif NETFRAMEWORK
- [ConditionalTheory]
- [FrameworkSkipCondition(RuntimeFrameworks.CoreCLR)]
- [MemberData(nameof(GetInts))]
- public void ThisTestMustRunOnCLR(int value)
- {
- Asserter.TestRan = true;
- }
-#else
-#error Target frameworks need to be updated.
-#endif
-
- // Test is named this way to be the lowest test in the alphabet, it relies on test ordering
- [Fact]
- public void ZzzzzzzEnsureThisIsTheLastTest()
- {
- Assert.True(Asserter.TestRan);
- }
-
- public static TheoryData<Func<int, int>> GetActionTestData
- => new TheoryData<Func<int, int>>
- {
- (i) => i * 1
- };
-
- public class ConditionalTheoryAsserter : IDisposable
- {
- public bool TestRan { get; set; }
-
- public void Dispose()
- {
- }
- }
-
- [ConditionalTheory]
- [MemberData(nameof(SkippableData))]
- public void WithSkipableData(Skippable skippable)
- {
- Assert.Null(skippable.Skip);
- Assert.Equal(1, skippable.Data);
- }
-
- public static TheoryData<Skippable> SkippableData => new TheoryData<Skippable>
- {
- new Skippable() { Data = 1 },
- new Skippable() { Data = 2, Skip = "This row should be skipped." }
- };
-
- public class Skippable : IXunitSerializable
- {
- public Skippable() { }
- public int Data { get; set; }
- public string Skip { get; set; }
-
- public void Serialize(IXunitSerializationInfo info)
- {
- info.AddValue(nameof(Data), Data, typeof(int));
- }
-
- public void Deserialize(IXunitSerializationInfo info)
- {
- Data = info.GetValue<int>(nameof(Data));
- }
-
- public override string ToString()
- {
- return Data.ToString();
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Runtime.InteropServices;
-using Microsoft.AspNetCore.Testing;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class DockerTests
- {
- [ConditionalFact]
- [DockerOnly]
- [Trait("Docker", "true")]
- public void DoesNotRunOnWindows()
- {
- Assert.False(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class EnvironmentVariableSkipConditionTest
- {
- private readonly string _skipReason = "Test skipped on environment variable with name '{0}' and value '{1}'" +
- $" for the '{nameof(EnvironmentVariableSkipConditionAttribute.RunOnMatch)}' value of '{{2}}'.";
-
- [Theory]
- [InlineData("false")]
- [InlineData("")]
- [InlineData(null)]
- public void IsMet_DoesNotMatch(string environmentVariableValue)
- {
- // Arrange
- var attribute = new EnvironmentVariableSkipConditionAttribute(
- new TestEnvironmentVariable("Run", environmentVariableValue),
- "Run",
- "true");
-
- // Act
- var isMet = attribute.IsMet;
-
- // Assert
- Assert.False(isMet);
- }
-
- [Theory]
- [InlineData("True")]
- [InlineData("TRUE")]
- [InlineData("true")]
- public void IsMet_DoesCaseInsensitiveMatch_OnValue(string environmentVariableValue)
- {
- // Arrange
- var attribute = new EnvironmentVariableSkipConditionAttribute(
- new TestEnvironmentVariable("Run", environmentVariableValue),
- "Run",
- "true");
-
- // Act
- var isMet = attribute.IsMet;
-
- // Assert
- Assert.True(isMet);
- Assert.Equal(
- string.Format(_skipReason, "Run", environmentVariableValue, attribute.RunOnMatch),
- attribute.SkipReason);
- }
-
- [Fact]
- public void IsMet_DoesSuccessfulMatch_OnNull()
- {
- // Arrange
- var attribute = new EnvironmentVariableSkipConditionAttribute(
- new TestEnvironmentVariable("Run", null),
- "Run",
- "true", null); // skip the test when the variable 'Run' is explicitly set to 'true' or is null (default)
-
- // Act
- var isMet = attribute.IsMet;
-
- // Assert
- Assert.True(isMet);
- Assert.Equal(
- string.Format(_skipReason, "Run", "(null)", attribute.RunOnMatch),
- attribute.SkipReason);
- }
-
- [Theory]
- [InlineData("false")]
- [InlineData("")]
- [InlineData(null)]
- public void IsMet_MatchesOnMultipleSkipValues(string environmentVariableValue)
- {
- // Arrange
- var attribute = new EnvironmentVariableSkipConditionAttribute(
- new TestEnvironmentVariable("Run", environmentVariableValue),
- "Run",
- "false", "", null);
-
- // Act
- var isMet = attribute.IsMet;
-
- // Assert
- Assert.True(isMet);
- }
-
- [Fact]
- public void IsMet_DoesNotMatch_OnMultipleSkipValues()
- {
- // Arrange
- var attribute = new EnvironmentVariableSkipConditionAttribute(
- new TestEnvironmentVariable("Build", "100"),
- "Build",
- "125", "126");
-
- // Act
- var isMet = attribute.IsMet;
-
- // Assert
- Assert.False(isMet);
- }
-
- [Theory]
- [InlineData("CentOS")]
- [InlineData(null)]
- [InlineData("")]
- public void IsMet_Matches_WhenRunOnMatchIsFalse(string environmentVariableValue)
- {
- // Arrange
- var attribute = new EnvironmentVariableSkipConditionAttribute(
- new TestEnvironmentVariable("LinuxFlavor", environmentVariableValue),
- "LinuxFlavor",
- "Ubuntu14.04")
- {
- // Example: Run this test on all OSes except on "Ubuntu14.04"
- RunOnMatch = false
- };
-
- // Act
- var isMet = attribute.IsMet;
-
- // Assert
- Assert.True(isMet);
- }
-
- [Fact]
- public void IsMet_DoesNotMatch_WhenRunOnMatchIsFalse()
- {
- // Arrange
- var attribute = new EnvironmentVariableSkipConditionAttribute(
- new TestEnvironmentVariable("LinuxFlavor", "Ubuntu14.04"),
- "LinuxFlavor",
- "Ubuntu14.04")
- {
- // Example: Run this test on all OSes except on "Ubuntu14.04"
- RunOnMatch = false
- };
-
- // Act
- var isMet = attribute.IsMet;
-
- // Assert
- Assert.False(isMet);
- }
-
- private struct TestEnvironmentVariable : IEnvironmentVariable
- {
- private readonly string _varName;
-
- public TestEnvironmentVariable(string varName, string value)
- {
- _varName = varName;
- Value = value;
- }
-
- public string Value { get; private set; }
-
- public string Get(string name)
- {
- if(string.Equals(name, _varName, System.StringComparison.OrdinalIgnoreCase))
- {
- return Value;
- }
- return string.Empty;
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class ExceptionAssertTest
- {
- [Fact]
- [ReplaceCulture("fr-FR", "fr-FR")]
- public void AssertArgumentNullOrEmptyString_WorksInNonEnglishCultures()
- {
- // Arrange
- Action action = () =>
- {
- throw new ArgumentException("Value cannot be null or an empty string.", "foo");
- };
-
- // Act and Assert
- ExceptionAssert.ThrowsArgumentNullOrEmptyString(action, "foo");
- }
-
- [Fact]
- [ReplaceCulture("fr-FR", "fr-FR")]
- public void AssertArgumentOutOfRangeException_WorksInNonEnglishCultures()
- {
- // Arrange
- Action action = () =>
- {
- throw new ArgumentOutOfRangeException("foo", 10, "exception message.");
- };
-
- // Act and Assert
- ExceptionAssert.ThrowsArgumentOutOfRange(action, "foo", "exception message.", 10);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Collections.Generic;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing.Tests
-{
- public class FlakyAttributeTest
- {
- [Fact(Skip = "These tests are nice when you need them but annoying when on all the time.")]
- [Flaky("http://example.com", FlakyOn.All)]
- public void AlwaysFlakyInCI()
- {
- if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HELIX")) || !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AGENT_OS")))
- {
- throw new Exception("Flaky!");
- }
- }
-
- [Fact(Skip = "These tests are nice when you need them but annoying when on all the time.")]
- [Flaky("http://example.com", FlakyOn.Helix.All)]
- public void FlakyInHelixOnly()
- {
- if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HELIX")))
- {
- throw new Exception("Flaky on Helix!");
- }
- }
-
- [Fact(Skip = "These tests are nice when you need them but annoying when on all the time.")]
- [Flaky("http://example.com", FlakyOn.Helix.macOS1012Amd64, FlakyOn.Helix.Fedora28Amd64)]
- public void FlakyInSpecificHelixQueue()
- {
- // Today we don't run Extensions tests on Helix, but this test should light up when we do.
- var queueName = Environment.GetEnvironmentVariable("HELIX");
- if (!string.IsNullOrEmpty(queueName))
- {
- var failingQueues = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { HelixQueues.macOS1012Amd64, HelixQueues.Fedora28Amd64 };
- if (failingQueues.Contains(queueName))
- {
- throw new Exception($"Flaky on Helix Queue '{queueName}' !");
- }
- }
- }
-
- [Fact(Skip = "These tests are nice when you need them but annoying when on all the time.")]
- [Flaky("http://example.com", FlakyOn.AzP.All)]
- public void FlakyInAzPOnly()
- {
- if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AGENT_OS")))
- {
- throw new Exception("Flaky on AzP!");
- }
- }
-
- [Fact(Skip = "These tests are nice when you need them but annoying when on all the time.")]
- [Flaky("http://example.com", FlakyOn.AzP.Windows)]
- public void FlakyInAzPWindowsOnly()
- {
- if (string.Equals(Environment.GetEnvironmentVariable("AGENT_OS"), "Windows_NT"))
- {
- throw new Exception("Flaky on AzP Windows!");
- }
- }
-
- [Fact(Skip = "These tests are nice when you need them but annoying when on all the time.")]
- [Flaky("http://example.com", FlakyOn.AzP.macOS)]
- public void FlakyInAzPmacOSOnly()
- {
- if (string.Equals(Environment.GetEnvironmentVariable("AGENT_OS"), "Darwin"))
- {
- throw new Exception("Flaky on AzP macOS!");
- }
- }
-
- [Fact(Skip = "These tests are nice when you need them but annoying when on all the time.")]
- [Flaky("http://example.com", FlakyOn.AzP.Linux)]
- public void FlakyInAzPLinuxOnly()
- {
- if (string.Equals(Environment.GetEnvironmentVariable("AGENT_OS"), "Linux"))
- {
- throw new Exception("Flaky on AzP Linux!");
- }
- }
-
- [Fact(Skip = "These tests are nice when you need them but annoying when on all the time.")]
- [Flaky("http://example.com", FlakyOn.AzP.Linux, FlakyOn.AzP.macOS)]
- public void FlakyInAzPNonWindowsOnly()
- {
- var agentOs = Environment.GetEnvironmentVariable("AGENT_OS");
- if (string.Equals(agentOs, "Linux") || string.Equals(agentOs, "Darwin"))
- {
- throw new Exception("Flaky on AzP non-Windows!");
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Net;
-using System.Net.Http;
-using System.Text;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class HttpClientSlimTest
- {
- private static readonly byte[] _defaultResponse = Encoding.ASCII.GetBytes("test");
-
- [Fact]
- public async Task GetStringAsyncHttp()
- {
- using (var host = StartHost(out var address))
- {
- Assert.Equal("test", await HttpClientSlim.GetStringAsync(address));
- }
- }
-
- [Fact]
- public async Task GetStringAsyncThrowsForErrorResponse()
- {
- using (var host = StartHost(out var address, statusCode: 500))
- {
- await Assert.ThrowsAnyAsync<HttpRequestException>(() => HttpClientSlim.GetStringAsync(address));
- }
- }
-
- [Fact]
- public async Task PostAsyncHttp()
- {
- using (var host = StartHost(out var address, handler: context => context.Request.InputStream.CopyToAsync(context.Response.OutputStream)))
- {
- Assert.Equal("test post", await HttpClientSlim.PostAsync(address, new StringContent("test post")));
- }
- }
-
- [Fact]
- public async Task PostAsyncThrowsForErrorResponse()
- {
- using (var host = StartHost(out var address, statusCode: 500))
- {
- await Assert.ThrowsAnyAsync<HttpRequestException>(
- () => HttpClientSlim.PostAsync(address, new StringContent("")));
- }
- }
-
- [Fact]
- public void Ipv6ScopeIdsFilteredOut()
- {
- var requestUri = new Uri("http://[fe80::5d2a:d070:6fd6:1bac%7]:5003/");
- Assert.Equal("[fe80::5d2a:d070:6fd6:1bac]:5003", HttpClientSlim.GetHost(requestUri));
- }
-
- [Fact]
- public void GetHostExcludesDefaultPort()
- {
- var requestUri = new Uri("http://[fe80::5d2a:d070:6fd6:1bac%7]:80/");
- Assert.Equal("[fe80::5d2a:d070:6fd6:1bac]", HttpClientSlim.GetHost(requestUri));
- }
-
- private HttpListener StartHost(out string address, int statusCode = 200, Func<HttpListenerContext, Task> handler = null)
- {
- var listener = new HttpListener();
- var random = new Random();
- address = null;
-
- for (var i = 0; i < 10; i++)
- {
- try
- {
- // HttpListener doesn't support requesting port 0 (dynamic).
- // Requesting port 0 from Sockets and then passing that to HttpListener is racy.
- // Just keep trying until we find a free one.
- address = $"http://localhost:{random.Next(1024, ushort.MaxValue)}/";
- listener.Prefixes.Add(address);
- listener.Start();
- break;
- }
- catch (HttpListenerException)
- {
- // Address in use
- listener.Close();
- listener = new HttpListener();
- }
- }
-
- Assert.True(listener.IsListening, "IsListening");
-
- _ = listener.GetContextAsync().ContinueWith(async task =>
- {
- var context = task.Result;
- context.Response.StatusCode = statusCode;
-
- if (handler == null)
- {
- await context.Response.OutputStream.WriteAsync(_defaultResponse, 0, _defaultResponse.Length);
- }
- else
- {
- await handler(context);
- }
-
- context.Response.Close();
- });
-
- return listener;
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class MaximumOSVersionAttributeTest
- {
- [Fact]
- public void Linux_ThrowsNotImplemeneted()
- {
- Assert.Throws<NotImplementedException>(() => new MaximumOSVersionAttribute(OperatingSystems.Linux, "2.5"));
- }
-
- [Fact]
- public void Mac_ThrowsNotImplemeneted()
- {
- Assert.Throws<NotImplementedException>(() => new MaximumOSVersionAttribute(OperatingSystems.MacOSX, "2.5"));
- }
-
- [Fact]
- public void WindowsOrLinux_ThrowsNotImplemeneted()
- {
- Assert.Throws<NotImplementedException>(() => new MaximumOSVersionAttribute(OperatingSystems.Linux | OperatingSystems.Windows, "2.5"));
- }
-
- [Fact]
- public void DoesNotSkip_ShortVersions()
- {
- var osSkipAttribute = new MaximumOSVersionAttribute(
- OperatingSystems.Windows,
- new Version("2.5"),
- OperatingSystems.Windows,
- new Version("2.0"));
-
- Assert.True(osSkipAttribute.IsMet);
- }
-
- [Fact]
- public void DoesNotSkip_EarlierVersions()
- {
- var osSkipAttribute = new MaximumOSVersionAttribute(
- OperatingSystems.Windows,
- new Version("2.5.9"),
- OperatingSystems.Windows,
- new Version("2.0.10.12"));
-
- Assert.True(osSkipAttribute.IsMet);
- }
-
- [Fact]
- public void DoesNotSkip_SameVersion()
- {
- var osSkipAttribute = new MaximumOSVersionAttribute(
- OperatingSystems.Windows,
- new Version("2.5.10"),
- OperatingSystems.Windows,
- new Version("2.5.10.12"));
-
- Assert.True(osSkipAttribute.IsMet);
- }
-
- [Fact]
- public void Skip_LaterVersion()
- {
- var osSkipAttribute = new MaximumOSVersionAttribute(
- OperatingSystems.Windows,
- new Version("2.5.11"),
- OperatingSystems.Windows,
- new Version("3.0.10.12"));
-
- Assert.False(osSkipAttribute.IsMet);
- }
-
- [Fact]
- public void DoesNotSkip_WhenOnlyVersionsMatch()
- {
- var osSkipAttribute = new MaximumOSVersionAttribute(
- OperatingSystems.Windows,
- new Version("2.5.10.12"),
- OperatingSystems.Linux,
- new Version("2.5.10.12"));
-
- Assert.True(osSkipAttribute.IsMet);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Runtime.InteropServices;
-using Microsoft.Win32;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
- public class MaximumOSVersionTest
- {
- [ConditionalFact]
- [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win7)]
- public void RunTest_Win7DoesRunOnWin7()
- {
- Assert.True(
- RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
- Environment.OSVersion.Version.ToString().StartsWith("6.1"),
- "Test should only be running on Win7 or Win2008R2.");
- }
-
- [ConditionalTheory]
- [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win7)]
- [InlineData(1)]
- public void RunTheory_Win7DoesRunOnWin7(int arg)
- {
- Assert.True(
- RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
- Environment.OSVersion.Version.ToString().StartsWith("6.1"),
- "Test should only be running on Win7 or Win2008R2.");
- }
-
- [ConditionalFact]
- [FrameworkSkipCondition(RuntimeFrameworks.CLR, SkipReason = "https://github.com/xunit/xunit/issues/2076")]
- [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_RS4)]
- [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
- public void RunTest_Win10_RS4()
- {
- Assert.True(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
- var versionKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
- Assert.NotNull(versionKey);
- var currentVersion = (string)versionKey.GetValue("CurrentBuildNumber");
- Assert.NotNull(currentVersion);
- Assert.True(17134 >= int.Parse(currentVersion), $"Unexpected build number {currentVersion} on {Environment.OSVersion.Version}.");
- }
-
- [ConditionalFact]
- [FrameworkSkipCondition(RuntimeFrameworks.CLR, SkipReason = "https://github.com/xunit/xunit/issues/2076")]
- [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_19H2)]
- [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
- public void RunTest_Win10_19H2()
- {
- Assert.True(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
- var versionKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
- Assert.NotNull(versionKey);
- var currentVersion = (string)versionKey.GetValue("CurrentBuildNumber");
- Assert.NotNull(currentVersion);
- Assert.True(18363 >= int.Parse(currentVersion), $"Unexpected build number {currentVersion} on {Environment.OSVersion.Version}.");
- }
- }
-
- [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win7)]
- [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
- public class OSMaxVersionClassTest
- {
- [ConditionalFact]
- public void TestSkipClass_Win7DoesRunOnWin7()
- {
- Assert.True(
- RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
- Environment.OSVersion.Version.ToString().StartsWith("6.1"),
- "Test should only be running on Win7 or Win2008R2.");
- }
- }
-
- // Let this one run cross plat just to check the constructor logic.
- [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win7)]
- public class OSMaxVersionCrossPlatTest
- {
- [ConditionalFact]
- public void TestSkipClass_Win7DoesRunOnWin7()
- {
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- {
- Assert.True(Environment.OSVersion.Version.ToString().StartsWith("6.1"),
- "Test should only be running on Win7 or Win2008R2.");
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class MinimumOSVersionAttributeTest
- {
- [Fact]
- public void Linux_ThrowsNotImplemeneted()
- {
- Assert.Throws<NotImplementedException>(() => new MinimumOSVersionAttribute(OperatingSystems.Linux, "2.5"));
- }
-
- [Fact]
- public void Mac_ThrowsNotImplemeneted()
- {
- Assert.Throws<NotImplementedException>(() => new MinimumOSVersionAttribute(OperatingSystems.MacOSX, "2.5"));
- }
-
- [Fact]
- public void WindowsOrLinux_ThrowsNotImplemeneted()
- {
- Assert.Throws<NotImplementedException>(() => new MinimumOSVersionAttribute(OperatingSystems.Linux | OperatingSystems.Windows, "2.5"));
- }
-
- [Fact]
- public void DoesNotSkip_LaterVersions()
- {
- var osSkipAttribute = new MinimumOSVersionAttribute(
- OperatingSystems.Windows,
- new Version("2.0"),
- OperatingSystems.Windows,
- new Version("2.5"));
-
- Assert.True(osSkipAttribute.IsMet);
- }
-
- [Fact]
- public void DoesNotSkip_SameVersion()
- {
- var osSkipAttribute = new MinimumOSVersionAttribute(
- OperatingSystems.Windows,
- new Version("2.5"),
- OperatingSystems.Windows,
- new Version("2.5"));
-
- Assert.True(osSkipAttribute.IsMet);
- }
-
- [Fact]
- public void Skip_EarlierVersion()
- {
- var osSkipAttribute = new MinimumOSVersionAttribute(
- OperatingSystems.Windows,
- new Version("3.0"),
- OperatingSystems.Windows,
- new Version("2.5"));
-
- Assert.False(osSkipAttribute.IsMet);
- }
-
- [Fact]
- public void DoesNotSkip_WhenOnlyVersionsMatch()
- {
- var osSkipAttribute = new MinimumOSVersionAttribute(
- OperatingSystems.Windows,
- new Version("2.5"),
- OperatingSystems.Linux,
- new Version("2.5"));
-
- Assert.True(osSkipAttribute.IsMet);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Runtime.InteropServices;
-using Microsoft.Win32;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class MinimumOSVersionTest
- {
- [ConditionalFact]
- [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win8)]
- public void RunTest_Win8DoesNotRunOnWin7()
- {
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
- Environment.OSVersion.Version.ToString().StartsWith("6.1"),
- "Test should not be running on Win7 or Win2008R2.");
- }
-
- [ConditionalTheory]
- [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win8)]
- [InlineData(1)]
- public void RunTheory_Win8DoesNotRunOnWin7(int arg)
- {
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
- Environment.OSVersion.Version.ToString().StartsWith("6.1"),
- "Test should not be running on Win7 or Win2008R2.");
- }
-
- [ConditionalFact]
- [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_RS4)]
- [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
- public void RunTest_Win10_RS4()
- {
- Assert.True(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
- var versionKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
- Assert.NotNull(versionKey);
- var currentVersion = (string)versionKey.GetValue("CurrentBuildNumber");
- Assert.NotNull(currentVersion);
- Assert.True(17134 <= int.Parse(currentVersion));
- }
-
- [ConditionalFact]
- [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_19H2)]
- [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
- public void RunTest_Win10_19H2()
- {
- Assert.True(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
- var versionKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
- Assert.NotNull(versionKey);
- var currentVersion = (string)versionKey.GetValue("CurrentBuildNumber");
- Assert.NotNull(currentVersion);
- Assert.True(18363 <= int.Parse(currentVersion));
- }
- }
-
- [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win8)]
- public class OSMinVersionClassTest
- {
- [ConditionalFact]
- public void TestSkipClass_Win8DoesNotRunOnWin7()
- {
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
- Environment.OSVersion.Version.ToString().StartsWith("6.1"),
- "Test should not be running on Win7 or Win2008R2.");
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Runtime.InteropServices;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class OSSkipConditionAttributeTest
- {
- [Fact]
- public void Skips_WhenOperatingSystemMatches()
- {
- // Act
- var osSkipAttribute = new OSSkipConditionAttribute(
- OperatingSystems.Windows,
- OperatingSystems.Windows);
-
- // Assert
- Assert.False(osSkipAttribute.IsMet);
- }
-
- [Fact]
- public void DoesNotSkip_WhenOperatingSystemDoesNotMatch()
- {
- // Act
- var osSkipAttribute = new OSSkipConditionAttribute(
- OperatingSystems.Linux,
- OperatingSystems.Windows);
-
- // Assert
- Assert.True(osSkipAttribute.IsMet);
- }
-
- [Fact]
- public void Skips_BothMacOSXAndLinux()
- {
- // Act
- var osSkipAttributeLinux = new OSSkipConditionAttribute(OperatingSystems.Linux | OperatingSystems.MacOSX, OperatingSystems.Linux);
- var osSkipAttributeMacOSX = new OSSkipConditionAttribute(OperatingSystems.Linux | OperatingSystems.MacOSX, OperatingSystems.MacOSX);
-
- // Assert
- Assert.False(osSkipAttributeLinux.IsMet);
- Assert.False(osSkipAttributeMacOSX.IsMet);
- }
-
- [Fact]
- public void Skips_BothMacOSXAndWindows()
- {
- // Act
- var osSkipAttribute = new OSSkipConditionAttribute(OperatingSystems.Windows | OperatingSystems.MacOSX, OperatingSystems.Windows);
- var osSkipAttributeMacOSX = new OSSkipConditionAttribute(OperatingSystems.Windows | OperatingSystems.MacOSX, OperatingSystems.MacOSX);
-
- // Assert
- Assert.False(osSkipAttribute.IsMet);
- Assert.False(osSkipAttributeMacOSX.IsMet);
- }
-
- [Fact]
- public void Skips_BothWindowsAndLinux()
- {
- // Act
- var osSkipAttribute = new OSSkipConditionAttribute(OperatingSystems.Linux | OperatingSystems.Windows, OperatingSystems.Windows);
- var osSkipAttributeLinux = new OSSkipConditionAttribute(OperatingSystems.Linux | OperatingSystems.Windows, OperatingSystems.Linux);
-
- // Assert
- Assert.False(osSkipAttribute.IsMet);
- Assert.False(osSkipAttributeLinux.IsMet);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System.Runtime.InteropServices;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class OSSkipConditionTest
- {
- [ConditionalFact]
- [OSSkipCondition(OperatingSystems.Linux)]
- public void TestSkipLinux()
- {
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.Linux),
- "Test should not be running on Linux");
- }
-
- [ConditionalFact]
- [OSSkipCondition(OperatingSystems.MacOSX)]
- public void TestSkipMacOSX()
- {
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.OSX),
- "Test should not be running on MacOSX.");
- }
-
- [ConditionalFact]
- [OSSkipCondition(OperatingSystems.Windows)]
- public void TestSkipWindows()
- {
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.Windows),
- "Test should not be running on Windows.");
- }
-
- [ConditionalFact]
- [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
- public void TestSkipLinuxAndMacOSX()
- {
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.Linux),
- "Test should not be running on Linux.");
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.OSX),
- "Test should not be running on MacOSX.");
- }
-
- [ConditionalTheory]
- [OSSkipCondition(OperatingSystems.Linux)]
- [InlineData(1)]
- public void TestTheorySkipLinux(int arg)
- {
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.Linux),
- "Test should not be running on Linux");
- }
-
- [ConditionalTheory]
- [OSSkipCondition(OperatingSystems.MacOSX)]
- [InlineData(1)]
- public void TestTheorySkipMacOS(int arg)
- {
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.OSX),
- "Test should not be running on MacOSX.");
- }
-
- [ConditionalTheory]
- [OSSkipCondition(OperatingSystems.Windows)]
- [InlineData(1)]
- public void TestTheorySkipWindows(int arg)
- {
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.Windows),
- "Test should not be running on Windows.");
- }
-
- [ConditionalTheory]
- [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
- [InlineData(1)]
- public void TestTheorySkipLinuxAndMacOSX(int arg)
- {
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.Linux),
- "Test should not be running on Linux.");
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.OSX),
- "Test should not be running on MacOSX.");
- }
- }
-
- [OSSkipCondition(OperatingSystems.Windows)]
- public class OSSkipConditionClassTest
- {
- [ConditionalFact]
- public void TestSkipClassWindows()
- {
- Assert.False(
- RuntimeInformation.IsOSPlatform(OSPlatform.Windows),
- "Test should not be running on Windows.");
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using Microsoft.AspNetCore.Testing;
-using Xunit;
-
-[assembly: Repeat(1)]
-[assembly: AssemblyFixture(typeof(TestAssemblyFixture))]
-[assembly: TestFramework("Microsoft.AspNetCore.Testing.AspNetTestFramework", "Microsoft.AspNetCore.Testing")]
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- [Repeat]
- public class RepeatTest
- {
- public static int _runCount = 0;
-
- [Fact]
- [Repeat(5)]
- public void RepeatLimitIsSetCorrectly()
- {
- Assert.Equal(5, RepeatContext.Current.Limit);
- }
-
- [Fact]
- [Repeat(5)]
- public void RepeatRunsTestSpecifiedNumberOfTimes()
- {
- Assert.Equal(RepeatContext.Current.CurrentIteration, _runCount);
- _runCount++;
- }
-
- [Fact]
- public void RepeatCanBeSetOnClass()
- {
- Assert.Equal(10, RepeatContext.Current.Limit);
- }
- }
-
- public class LoggedTestXunitRepeatAssemblyTests
- {
- [Fact]
- public void RepeatCanBeSetOnAssembly()
- {
- Assert.Equal(1, RepeatContext.Current.Limit);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System.Globalization;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class RepalceCultureAttributeTest
- {
- [Fact]
- public void DefaultsTo_EnGB_EnUS()
- {
- // Arrange
- var culture = new CultureInfo("en-GB");
- var uiCulture = new CultureInfo("en-US");
-
- // Act
- var replaceCulture = new ReplaceCultureAttribute();
-
- // Assert
- Assert.Equal(culture, replaceCulture.Culture);
- Assert.Equal(uiCulture, replaceCulture.UICulture);
- }
-
- [Fact]
- public void UsesSuppliedCultureAndUICulture()
- {
- // Arrange
- var culture = "de-DE";
- var uiCulture = "fr-CA";
-
- // Act
- var replaceCulture = new ReplaceCultureAttribute(culture, uiCulture);
-
- // Assert
- Assert.Equal(new CultureInfo(culture), replaceCulture.Culture);
- Assert.Equal(new CultureInfo(uiCulture), replaceCulture.UICulture);
- }
-
- [Fact]
- public void BeforeAndAfterTest_ReplacesCulture()
- {
- // Arrange
- var originalCulture = CultureInfo.CurrentCulture;
- var originalUICulture = CultureInfo.CurrentUICulture;
- var culture = "de-DE";
- var uiCulture = "fr-CA";
- var replaceCulture = new ReplaceCultureAttribute(culture, uiCulture);
-
- // Act
- replaceCulture.Before(methodUnderTest: null);
-
- // Assert
- Assert.Equal(new CultureInfo(culture), CultureInfo.CurrentCulture);
- Assert.Equal(new CultureInfo(uiCulture), CultureInfo.CurrentUICulture);
-
- // Act
- replaceCulture.After(methodUnderTest: null);
-
- // Assert
- Assert.Equal(originalCulture, CultureInfo.CurrentCulture);
- Assert.Equal(originalUICulture, CultureInfo.CurrentUICulture);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using Microsoft.AspNetCore.Testing;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing.Tests
-{
- public class SkipOnCITests
- {
- [ConditionalFact]
- [SkipOnCI]
- public void AlwaysSkipOnCI()
- {
- if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HELIX")) || !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AGENT_OS")))
- {
- throw new Exception("Flaky!");
- }
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class TaskExtensionsTest
- {
- [Fact]
- public async Task TimeoutAfterTest()
- {
- await Assert.ThrowsAsync<TimeoutException>(async () => await Task.Delay(1000).TimeoutAfter(TimeSpan.FromMilliseconds(50)));
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class TestAssemblyFixture
- {
- public int Count { get; set; }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class TestCollectionFixture
- {
- public int Count { get; set; }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class TestContextTest : ITestMethodLifecycle
- {
- public TestContext Context { get; private set; }
-
- [Fact]
- public void FullName_IsUsed_ByDefault()
- {
- Assert.Equal(GetType().FullName, Context.FileOutput.TestClassName);
- }
-
- Task ITestMethodLifecycle.OnTestStartAsync(TestContext context, CancellationToken cancellationToken)
- {
- Context = context;
- return Task.CompletedTask;
- }
-
- Task ITestMethodLifecycle.OnTestEndAsync(TestContext context, Exception exception, CancellationToken cancellationToken)
- {
- return Task.CompletedTask;
- }
- }
-}
-
-namespace Microsoft.AspNetCore.Testing.Tests
-{
- public class TestContextNameShorteningTest : ITestMethodLifecycle
- {
- public TestContext Context { get; private set; }
-
- [Fact]
- public void NameIsShortenedWhenAssemblyNameIsAPrefix()
- {
- Assert.Equal(GetType().Name, Context.FileOutput.TestClassName);
- }
-
- Task ITestMethodLifecycle.OnTestStartAsync(TestContext context, CancellationToken cancellationToken)
- {
- Context = context;
- return Task.CompletedTask;
- }
-
- Task ITestMethodLifecycle.OnTestEndAsync(TestContext context, Exception exception, CancellationToken cancellationToken)
- {
- return Task.CompletedTask;
- }
- }
-}
-
-namespace Microsoft.AspNetCore.Testing
-{
- [ShortClassName]
- public class TestContextTestClassShortNameAttributeTest : ITestMethodLifecycle
- {
- public TestContext Context { get; private set; }
-
- [Fact]
- public void ShortClassNameUsedWhenShortClassNameAttributeSpecified()
- {
- Assert.Equal(GetType().Name, Context.FileOutput.TestClassName);
- }
-
- Task ITestMethodLifecycle.OnTestStartAsync(TestContext context, CancellationToken cancellationToken)
- {
- Context = context;
- return Task.CompletedTask;
- }
-
- Task ITestMethodLifecycle.OnTestEndAsync(TestContext context, Exception exception, CancellationToken cancellationToken)
- {
- return Task.CompletedTask;
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System;
-using System.IO;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class TestPathUtilitiesTest
- {
- // Entire test pending removal - see https://github.com/dotnet/extensions/issues/1697
-#pragma warning disable 0618
-
- [Fact]
- public void GetSolutionRootDirectory_ResolvesSolutionRoot()
- {
- // Directory.GetCurrentDirectory() gives:
- // Testing\test\Microsoft.AspNetCore.Testing.Tests\bin\Debug\netcoreapp2.0
- // Testing\test\Microsoft.AspNetCore.Testing.Tests\bin\Debug\net461
- // Testing\test\Microsoft.AspNetCore.Testing.Tests\bin\Debug\net46
- var expectedPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "..", ".."));
-
- Assert.Equal(expectedPath, TestPathUtilities.GetSolutionRootDirectory("Extensions"));
- }
-
- [Fact]
- public void GetSolutionRootDirectory_Throws_IfNotFound()
- {
- var exception = Assert.Throws<Exception>(() => TestPathUtilities.GetSolutionRootDirectory("NotTesting"));
- Assert.Equal($"Solution file NotTesting.sln could not be found in {AppContext.BaseDirectory} or its parent directories.", exception.Message);
- }
-#pragma warning restore 0618
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using Microsoft.AspNetCore.Testing;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Testing
-{
- public class TestPlatformHelperTest
- {
- [ConditionalFact]
- [OSSkipCondition(OperatingSystems.MacOSX)]
- [OSSkipCondition(OperatingSystems.Windows)]
- public void IsLinux_TrueOnLinux()
- {
- Assert.True(TestPlatformHelper.IsLinux);
- Assert.False(TestPlatformHelper.IsMac);
- Assert.False(TestPlatformHelper.IsWindows);
- }
-
- [ConditionalFact]
- [OSSkipCondition(OperatingSystems.Linux)]
- [OSSkipCondition(OperatingSystems.Windows)]
- public void IsMac_TrueOnMac()
- {
- Assert.False(TestPlatformHelper.IsLinux);
- Assert.True(TestPlatformHelper.IsMac);
- Assert.False(TestPlatformHelper.IsWindows);
- }
-
- [ConditionalFact]
- [OSSkipCondition(OperatingSystems.Linux)]
- [OSSkipCondition(OperatingSystems.MacOSX)]
- public void IsWindows_TrueOnWindows()
- {
- Assert.False(TestPlatformHelper.IsLinux);
- Assert.False(TestPlatformHelper.IsMac);
- Assert.True(TestPlatformHelper.IsWindows);
- }
-
- [ConditionalFact]
- [FrameworkSkipCondition(RuntimeFrameworks.CLR | RuntimeFrameworks.CoreCLR | RuntimeFrameworks.None)]
- public void IsMono_TrueOnMono()
- {
- Assert.True(TestPlatformHelper.IsMono);
- }
-
- [ConditionalFact]
- [FrameworkSkipCondition(RuntimeFrameworks.Mono)]
- public void IsMono_FalseElsewhere()
- {
- Assert.False(TestPlatformHelper.IsMono);
- }
- }
-}
</PropertyGroup>
<ItemGroup>
- <Compile Include="..\..\Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\ExceptionAssertions.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\ExceptionAssertions.cs" />
- <Compile Include="..\..\Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\CultureReplacer.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\CultureReplacer.cs" />
- </ItemGroup>
-
- <ItemGroup>
<ProjectReference Include="..\src\Microsoft.Extensions.Caching.Memory.csproj" SkipUseReferenceAssembly="true" />
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.DependencyInjection\src\Microsoft.Extensions.DependencyInjection.csproj" />
</ItemGroup>
using System;
using System.Threading;
-using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Internal;
using Xunit;
var key = "myKey";
var value = new object();
- ExceptionAssert.ThrowsArgumentOutOfRange(() =>
- {
- var result = cache.Set(key, value, new MemoryCacheEntryOptions()
- .SetAbsoluteExpiration(TimeSpan.FromMinutes(-1)));
- },
- nameof(MemoryCacheEntryOptions.AbsoluteExpirationRelativeToNow),
- "The relative expiration value must be positive.",
- TimeSpan.FromMinutes(-1));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>(nameof(MemoryCacheEntryOptions.AbsoluteExpirationRelativeToNow), () =>
+ cache.Set(key, value, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(-1))));
}
[Fact]
var key = "myKey";
var value = new object();
- ExceptionAssert.ThrowsArgumentOutOfRange(() =>
- {
- var result = cache.Set(key, value, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.Zero));
- },
- nameof(MemoryCacheEntryOptions.AbsoluteExpirationRelativeToNow),
- "The relative expiration value must be positive.",
- TimeSpan.Zero);
+ AssertExtensions.Throws<ArgumentOutOfRangeException>(nameof(MemoryCacheEntryOptions.AbsoluteExpirationRelativeToNow), () =>
+ cache.Set(key, value, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.Zero)));
}
[Fact]
var key = "myKey";
var value = new object();
- ExceptionAssert.ThrowsArgumentOutOfRange(() =>
- {
- var result = cache.Set(key, value, new MemoryCacheEntryOptions()
- .SetSlidingExpiration(TimeSpan.FromMinutes(-1)));
- },
- nameof(MemoryCacheEntryOptions.SlidingExpiration),
- "The sliding expiration value must be positive.",
- TimeSpan.FromMinutes(-1));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>(nameof(MemoryCacheEntryOptions.SlidingExpiration), () =>
+ cache.Set(key, value, new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(-1))));
}
[Fact]
var key = "myKey";
var value = new object();
- ExceptionAssert.ThrowsArgumentOutOfRange(() =>
- {
- var result = cache.Set(key, value, new MemoryCacheEntryOptions()
- .SetSlidingExpiration(TimeSpan.Zero));
- },
- nameof(MemoryCacheEntryOptions.SlidingExpiration),
- "The sliding expiration value must be positive.",
- TimeSpan.Zero);
+ AssertExtensions.Throws<ArgumentOutOfRangeException>(nameof(MemoryCacheEntryOptions.SlidingExpiration), () =>
+ cache.Set(key, value, new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.Zero)));
}
[Fact]
Link="Microsoft.Extensions.Configuration\tests\Common\ConfigurationProviderExtensions.cs" />
<Compile Include="$(LibrariesProjectRoot)Microsoft.Extensions.Configuration\tests\Common\TestStreamHelpers.cs"
Link="Microsoft.Extensions.Configuration\tests\Common\TestStreamHelpers.cs" />
- <Compile Include="$(CommonTestPath)Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\ReplaceCulture.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\ReplaceCulture.cs" />
- <Compile Include="$(CommonTestPath)Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\xunit\FrameworkSkipConditionAttribute.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\xunit\FrameworkSkipConditionAttribute.cs" />
- <Compile Include="$(CommonTestPath)Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\xunit\ITestCondition.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\xunit\ITestCondition.cs" />
- <Compile Include="$(CommonTestPath)Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\xunit\RuntimeFrameworks.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\xunit\RuntimeFrameworks.cs" />
- </ItemGroup>
-
- <ItemGroup Condition="'$(TargetFramework)' == 'net461'">
- <Compile Include="$(CommonTestPath)Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\TestPlatformHelper.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\TestPlatformHelper.cs" />
</ItemGroup>
<ItemGroup>
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
+using System.Tests;
using System.Xml;
-using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Configuration.Test;
using Xunit;
}
[Fact]
- [ReplaceCulture]
public void ThrowExceptionWhenFindDTD()
{
var xml =
</Inventory>
</Data>
</settings>";
- var xmlConfigSrc = new XmlConfigurationProvider(new XmlConfigurationSource());
- var isMono = Type.GetType("Mono.Runtime") != null;
- var expectedMsg = isMono ? "Document Type Declaration (DTD) is prohibited in this XML. Line 1, position 10." : "For security reasons DTD is prohibited in this XML document. "
- + "To enable DTD processing set the DtdProcessing property on XmlReaderSettings "
- + "to Parse and pass the settings into XmlReader.Create method.";
- var exception = Assert.Throws<System.Xml.XmlException>(() => xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)));
+ using (new ThreadCultureChange("en-GB"))
+ {
+ var xmlConfigSrc = new XmlConfigurationProvider(new XmlConfigurationSource());
+ var isMono = Type.GetType("Mono.Runtime") != null;
+ var expectedMsg = isMono ? "Document Type Declaration (DTD) is prohibited in this XML. Line 1, position 10." : "For security reasons DTD is prohibited in this XML document. "
+ + "To enable DTD processing set the DtdProcessing property on XmlReaderSettings "
+ + "to Parse and pass the settings into XmlReader.Create method.";
+
+ var exception = Assert.Throws<System.Xml.XmlException>(() => xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)));
- Assert.Equal(expectedMsg, exception.Message);
+ Assert.Equal(expectedMsg, exception.Message);
+ }
}
[Fact]
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/37669", TestPlatforms.Browser)]
- [FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public void LoadKeyValuePairsFromValidEncryptedXml()
{
var xml = @"
</PropertyGroup>
<ItemGroup>
- <Compile Include="$(CommonTestPath)Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\ExceptionAssertions.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\ExceptionAssertions.cs" />
- <Compile Include="$(CommonTestPath)Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\CultureReplacer.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\CultureReplacer.cs" />
<Compile Include="..\DI.Specification.Tests\**\*.cs" />
</ItemGroup>
</PropertyGroup>
<ItemGroup>
- <Compile Include="$(CommonTestPath)Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\ExceptionAssertions.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\ExceptionAssertions.cs" />
- <Compile Include="$(CommonTestPath)Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\CultureReplacer.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\CultureReplacer.cs" />
<Compile Include="..\DI.Specification.Tests\**\*.cs" />
</ItemGroup>
// The .NET Foundation licenses this file to you under the MIT license.
using System;
-using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.DependencyInjection.Specification.Fakes;
using Xunit;
// Arrange
var collection = new ServiceCollection();
- // Act & Assert
- ExceptionAssert.ThrowsArgument(
- () => collection.TryAddEnumerable(descriptor),
- "descriptor",
+ AssertExtensions.ThrowsContains<ArgumentException>(() => collection.TryAddEnumerable(descriptor),
string.Format(@"Implementation type cannot be '{0}' because it is indistinguishable from other services registered for '{1}'.", implementationType, serviceType));
}
using System;
using System.Collections.Generic;
using System.Linq;
-using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.Extensions.DependencyInjection
var serviceProvider = CreateTestServiceProvider(0);
// Act + Assert
- ExceptionAssert.Throws<InvalidOperationException>(() => serviceProvider.GetRequiredService<IFoo>(),
+ AssertExtensions.Throws<InvalidOperationException>(() => serviceProvider.GetRequiredService<IFoo>(),
$"No service for type '{typeof(IFoo)}' has been registered.");
}
var serviceProvider = new RequiredServiceSupportingProvider();
// Act + Assert
- ExceptionAssert.Throws<RankException>(() => serviceProvider.GetRequiredService<IFoo>());
+ AssertExtensions.Throws<RankException>(() => serviceProvider.GetRequiredService<IFoo>());
}
[Fact]
var serviceProvider = CreateTestServiceProvider(0);
// Act + Assert
- ExceptionAssert.Throws<InvalidOperationException>(() => serviceProvider.GetRequiredService(typeof(IFoo)),
+ AssertExtensions.Throws<InvalidOperationException>(() => serviceProvider.GetRequiredService(typeof(IFoo)),
$"No service for type '{typeof(IFoo)}' has been registered.");
}
var serviceProvider = new RequiredServiceSupportingProvider();
// Act + Assert
- ExceptionAssert.Throws<RankException>(() => serviceProvider.GetRequiredService(typeof(IFoo)));
+ AssertExtensions.Throws<RankException>(() => serviceProvider.GetRequiredService(typeof(IFoo)));
}
[Fact]
using System;
using System.Collections.Generic;
-using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.Extensions.DependencyInjection.ServiceLookup
};
// Act and Assert
- ExceptionAssert.ThrowsArgument(
- () => new CallSiteFactory(serviceDescriptors),
- "descriptors",
- $"Open generic service type '{typeof(IList<>)}' requires registering an open generic implementation type.");
+ AssertExtensions.Throws<ArgumentException>("descriptors", () => new CallSiteFactory(serviceDescriptors));
}
public static TheoryData Constructor_WithInstance_ThrowsIfServiceTypeIsOpenGenericData =>
};
// Act and Assert
- var ex = ExceptionAssert.ThrowsArgument(
- () => new CallSiteFactory(serviceDescriptors),
- "descriptors",
- $"Open generic service type '{typeof(IEnumerable<>)}' requires registering an open generic implementation type.");
+ AssertExtensions.Throws<ArgumentException>("descriptors", () => new CallSiteFactory(serviceDescriptors));
}
[Fact]
};
// Act and Assert
- var ex = ExceptionAssert.ThrowsArgument(
- () => new CallSiteFactory(serviceDescriptors),
- "descriptors",
- $"Open generic service type '{typeof(Tuple<>)}' requires registering an open generic implementation type.");
+ AssertExtensions.Throws<ArgumentException>("descriptors", () => new CallSiteFactory(serviceDescriptors));
}
}
}
</PropertyGroup>
<ItemGroup>
- <Compile Include="$(CommonTestPath)Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\xunit\ITestCondition.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\xunit\ITestCondition.cs" />
- <Compile Include="$(CommonTestPath)Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\TaskExtensions.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\TaskExtensions.cs" />
+ <Compile Include="$(CommonTestPath)System\Threading\Tasks\TaskTimeoutExtensions.cs"
+ Link="Common\System\Threading\Tasks\TaskTimeoutExtensions.cs" />
</ItemGroup>
<ItemGroup>
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.FileProviders.Internal;
using Microsoft.Extensions.FileProviders.Physical;
using Microsoft.Extensions.Primitives;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging;
namespace Microsoft.Extensions.Hosting.IntegrationTesting
<ItemGroup>
<Content Include="testroot\**\*" />
<Compile Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging\tests\Common\TestLoggerBuilder.cs" />
- <Compile Include="$(LibrariesProjectRoot)Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\TaskExtensions.cs"
- Link="TestingUtils\Microsoft.AspNetCore.Testing\src\TaskExtensions.cs" />
<Compile Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging\tests\DI.Common\Common\src\LogLevelAttribute.cs"
Link="tests\DI.Common\Common\src\LogLevelAttribute.cs" />
<Compile Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging\tests\DI.Common\Common\src\LogValuesAssert.cs"
</ItemGroup>
<ItemGroup>
+ <Compile Include="$(CommonTestPath)System\Threading\Tasks\TaskTimeoutExtensions.cs"
+ Link="Common\System\Threading\Tasks\TaskTimeoutExtensions.cs" />
+ </ItemGroup>
+
+ <ItemGroup>
<ProjectReference Include="..\TestApp\Microsoft.Extensions.Hosting.TestApp.csproj" />
</ItemGroup>
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Hosting.IntegrationTesting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Test;
</PropertyGroup>
<ItemGroup>
- <Compile Include="..\..\..\..\..\Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\ShortClassNameAttribute.cs"
- Link="Common\tests\Extensions\TestingUtils\Microsoft.AspNetCore.Testing\src\ShortClassNameAttribute.cs" />
<Compile Include="..\src\LogLevelAttribute.cs"
Link="tests\DI.Common\Common\src\LogLevelAttribute.cs" />
<Compile Include="..\src\LogValuesAssert.cs"