using System;
using System.Globalization;
using System.Reflection;
using System.Threading;
using Xunit.Sdk;
namespace Timeline.Tests.Helpers
{
// Copied from https://github.com/xunit/samples.xunit/blob/master/UseCulture/UseCultureAttribute.cs
///
/// Apply this attribute to your test method to replace the
/// and
/// with another culture.
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class UseCultureAttribute : BeforeAfterTestAttribute
{
readonly Lazy culture;
readonly Lazy uiCulture;
CultureInfo originalCulture;
CultureInfo originalUICulture;
///
/// Replaces the culture and UI culture of the current thread with
///
///
/// The name of the culture.
///
///
/// This constructor overload uses for both
/// and .
///
///
public UseCultureAttribute(string culture)
: this(culture, culture) { }
///
/// Replaces the culture and UI culture of the current thread with
/// and
///
/// The name of the culture.
/// The name of the UI culture.
public UseCultureAttribute(string culture, string uiCulture)
{
this.culture = new Lazy(() => new CultureInfo(culture, false));
this.uiCulture = new Lazy(() => new CultureInfo(uiCulture, false));
}
///
/// Gets the culture.
///
public CultureInfo Culture { get { return culture.Value; } }
///
/// Gets the UI culture.
///
public CultureInfo UICulture { get { return uiCulture.Value; } }
///
/// Stores the current
/// and
/// and replaces them with the new cultures defined in the constructor.
///
/// The method under test
public override void Before(MethodInfo methodUnderTest)
{
originalCulture = Thread.CurrentThread.CurrentCulture;
originalUICulture = Thread.CurrentThread.CurrentUICulture;
Thread.CurrentThread.CurrentCulture = Culture;
Thread.CurrentThread.CurrentUICulture = UICulture;
CultureInfo.CurrentCulture.ClearCachedData();
CultureInfo.CurrentUICulture.ClearCachedData();
}
///
/// Restores the original and
/// to
///
/// The method under test
public override void After(MethodInfo methodUnderTest)
{
Thread.CurrentThread.CurrentCulture = originalCulture;
Thread.CurrentThread.CurrentUICulture = originalUICulture;
CultureInfo.CurrentCulture.ClearCachedData();
CultureInfo.CurrentUICulture.ClearCachedData();
}
}
}