# Auto-generated from csapi-tizenfx.spec.in by makespec.sh
%define TIZEN_NET_API_VERSION 10
-%define TIZEN_NET_RPM_VERSION 10.0.0.999+nui22105
+%define TIZEN_NET_RPM_VERSION 10.0.0.999+nui22106
%define TIZEN_NET_NUGET_VERSION 10.0.0.99999
%define DOTNET_ASSEMBLY_PATH /usr/share/dotnet.tizen/framework
NUGET_VERSION=10.0.0.99999
# RPM Version Suffix
-RPM_VERSION_SUFFIX=nui22105
+RPM_VERSION_SUFFIX=nui22106
//FIXME: There is no way to know when system locale changed in NUI.
// Pickers order and Month text has to be follow system locale.
private void PickersOrderSet()
- {
- String locale = Environment.GetEnvironmentVariable("LC_TIME");
- DateTimeFormatInfo DateFormat = new CultureInfo(locale, false ).DateTimeFormat;
+ {
+ DateTimeFormatInfo DateFormat = CultureInfo.CurrentCulture.DateTimeFormat;
String temp = DateFormat.ShortDatePattern;
String[] strArray = temp.Split(' ', '/');
foreach (String format in strArray) {
private void SetMonthText()
{
- String locale = Environment.GetEnvironmentVariable("LC_TIME");
- CultureInfo info = new CultureInfo(locale);
+ CultureInfo info = CultureInfo.CurrentCulture;
monthPicker.DisplayedValues = new ReadOnlyCollection<string>(info.DateTimeFormat.AbbreviatedMonthNames);
}
}
/// DataTemplate of group header.
/// </summary>
/// <remarks>Please note that, internal index will be increased by group header.
- /// GroupHeaderTemplate is essential for groupable view.</remarks>
+ /// GroupHeaderTemplate is essential for groupable view.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public DataTemplate GroupHeaderTemplate
{
base.NotifyDataSetChanged();
}
- /// <inheritdoc/>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public override View GetNextFocusableView(View currentFocusedView, View.FocusDirection direction, bool loopEnabled)
- {
- View nextFocusedView = null;
-
- if (focusedView == null)
- {
- // If focusedView is null, find child which has previous data index
- if (ContentContainer.Children.Count > 0 && InternalItemSource.Count > 0)
- {
- for (int i = 0; i < ContentContainer.Children.Count; i++)
- {
- RecyclerViewItem item = Children[i] as RecyclerViewItem;
- if (item?.Index == prevFocusedDataIndex)
- {
- nextFocusedView = item;
- break;
- }
- }
- }
- }
- else
- {
- // If this is not first focus, request next focus to Layouter
- nextFocusedView = ItemsLayouter?.RequestNextFocusableView(currentFocusedView, direction, loopEnabled);
- }
-
- if (nextFocusedView != null)
- {
- // Check next focused view is inside of visible area.
- // If it is not, move scroll position to make it visible.
- Position scrollPosition = ContentContainer.CurrentPosition;
- float targetPosition = -(ScrollingDirection == Direction.Horizontal ? scrollPosition.X : scrollPosition.Y);
-
- float left = nextFocusedView.Position.X;
- float right = nextFocusedView.Position.X + nextFocusedView.Size.Width;
- float top = nextFocusedView.Position.Y;
- float bottom = nextFocusedView.Position.Y + nextFocusedView.Size.Height;
-
- float visibleRectangleLeft = -scrollPosition.X;
- float visibleRectangleRight = -scrollPosition.X + Size.Width;
- float visibleRectangleTop = -scrollPosition.Y;
- float visibleRectangleBottom = -scrollPosition.Y + Size.Height;
-
- if (ScrollingDirection == Direction.Horizontal)
- {
- if ((direction == View.FocusDirection.Left || direction == View.FocusDirection.Up) && left < visibleRectangleLeft)
- {
- targetPosition = left;
- }
- else if ((direction == View.FocusDirection.Right || direction == View.FocusDirection.Down) && right > visibleRectangleRight)
- {
- targetPosition = right - Size.Width;
- }
- }
- else
- {
- if ((direction == View.FocusDirection.Up || direction == View.FocusDirection.Left) && top < visibleRectangleTop)
- {
- targetPosition = top;
- }
- else if ((direction == View.FocusDirection.Down || direction == View.FocusDirection.Right) && bottom > visibleRectangleBottom)
- {
- targetPosition = bottom - Size.Height;
- }
- }
-
- focusedView = nextFocusedView;
- prevFocusedDataIndex = (nextFocusedView as RecyclerViewItem)?.Index ?? -1;
-
- ScrollTo(targetPosition, true);
- }
- else
- {
- // If nextView is null, it means that we should move focus to outside of Control.
- // Return FocusableView depending on direction.
- switch (direction)
- {
- case View.FocusDirection.Left:
- {
- nextFocusedView = LeftFocusableView;
- break;
- }
- case View.FocusDirection.Right:
- {
- nextFocusedView = RightFocusableView;
- break;
- }
- case View.FocusDirection.Up:
- {
- nextFocusedView = UpFocusableView;
- break;
- }
- case View.FocusDirection.Down:
- {
- nextFocusedView = DownFocusableView;
- break;
- }
- }
-
- if (nextFocusedView != null)
- {
- focusedView = null;
- }
- else
- {
- //If FocusableView doesn't exist, not move focus.
- nextFocusedView = focusedView;
- }
- }
-
- return nextFocusedView;
- }
-
/// <summary>
/// Update selected items list in multiple selection.
/// </summary>
{
item.Index = -1;
item.ParentItemsView = null;
- item.BindingContext = null;
+ item.BindingContext = null;
item.IsPressed = false;
item.IsSelected = false;
item.IsEnabled = true;
groupHeaderTemplate = null;
groupFooterTemplate = null;
- if (selectedItem != null)
+ if (selectedItem != null)
{
selectedItem = null;
}
{
selectedItem = null;
}
-
+
if (selectedItems != null)
{
foreach (object removed in args.OldItems)
Remove(ampmPicker);
//Get current system locale's time pattern
- String locale = Environment.GetEnvironmentVariable("LC_TIME");
- DateTimeFormatInfo timeFormatInfo = new CultureInfo(locale, false ).DateTimeFormat;
+ DateTimeFormatInfo timeFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat;
String timePattern = timeFormatInfo.ShortTimePattern;
String[] timePatternArray = timePattern.Split(' ', ':');
{
//FIXME: There is no localeChanged Event for Component now
// AMPM text has to update when system locale changed.
- String locale = Environment.GetEnvironmentVariable("LC_TIME");
- CultureInfo info = new CultureInfo(locale);
+ CultureInfo info = CultureInfo.CurrentCulture;
ampmText = new string[] {info.DateTimeFormat.AMDesignator, info.DateTimeFormat.PMDesignator};
ampmPicker.DisplayedValues = new ReadOnlyCollection<string>(ampmText);
}
public static extern global::System.IntPtr DaliToolkitDevelControlNotifyAccessibilityStatesChange(global::System.Runtime.InteropServices.HandleRef arg1, ulong arg2, int arg3);
[EditorBrowsable(EditorBrowsableState.Never)]
- [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Toolkit_DevelControl_GetBoundAccessibilityObject")]
- public static extern global::System.IntPtr DaliToolkitDevelControlGetBoundAccessibilityObject(global::System.Runtime.InteropServices.HandleRef arg1);
-
- [EditorBrowsable(EditorBrowsableState.Never)]
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Accessibility_EmitAccessibilityEvent")]
public static extern global::System.IntPtr DaliAccessibilityEmitAccessibilityEvent(global::System.Runtime.InteropServices.HandleRef arg1, int arg2_event);
public View GetCurrentlyHighlightedView()
{
var ptr = Interop.ControlDevel.DaliAccessibilityAccessibleGetCurrentlyHighlightedActor();
+
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
- if (ptr == IntPtr.Zero)
- return null;
- return new View(ptr, true);
+
+ return this.GetInstanceSafely<View>(ptr);
}
/// <summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ClearCurrentlyHighlightedView()
{
- using (View view = GetCurrentlyHighlightedView())
- {
- return view?.ClearAccessibilityHighlight() ?? false;
- }
+ var view = GetCurrentlyHighlightedView();
+
+ return view?.ClearAccessibilityHighlight() ?? false;
}
#endregion Method
get
{
int ret = -1;
- PropertyMap map = Image;
+ PropertyMap map = base.Image;
if (map != null)
{
PropertyValue val = map.Find(ImageVisualProperty.TotalFrameNumber);
get
{
int ret = -1;
- PropertyMap map = Image;
+ PropertyMap map = base.Image;
if (map != null)
{
PropertyValue val = map.Find(ImageVisualProperty.CurrentFrameNumber);
{
if (_border == null)
{
- // Sync as current properties.
- UpdateImage();
-
- return _imagePropertyMap == null ? new PropertyMap() : new PropertyMap(_imagePropertyMap);
+ // Get current properties force.
+ // TODO: Need to make some flag that we only need cached property map.
+ PropertyMap returnValue = new PropertyMap();
+ PropertyValue image = GetProperty(ImageView.Property.IMAGE);
+ image?.Get(returnValue);
+ image?.Dispose();
+ return returnValue;
}
else
{
var imageView = (ImageView)bindable;
if (imageView._border == null)
{
+ // Get current properties force.
+ // TODO: Need to make some flag that we only need cached property map.
PropertyMap temp = new PropertyMap();
-
- // Sync as current properties.
- imageView.UpdateImage();
- if(imageView._imagePropertyMap != null)
- {
- temp.Merge(imageView._imagePropertyMap);
- }
-
+ Tizen.NUI.Object.GetProperty((HandleRef)imageView.SwigCPtr, ImageView.Property.IMAGE).Get(temp);
return temp;
}
else
string ret = currentStates.url;
NUILog.Debug($"<[{GetId()}] GET");
- PropertyMap map = Image;
+ PropertyMap map = base.Image;
if (map != null)
{
PropertyValue val = map.Find(ImageVisualProperty.URL);
get
{
int ret = -1;
- PropertyMap map = Image;
+ PropertyMap map = base.Image;
if (map != null)
{
PropertyValue val = map.Find(ImageVisualProperty.TotalFrameNumber);
get
{
int ret = 0;
- PropertyMap map = Image;
+ PropertyMap map = base.Image;
if (map != null)
{
PropertyValue val = map.Find(ImageVisualProperty.CurrentFrameNumber);
NUILog.Debug($"<[{GetId()}] SET loopMode={currentStates.loopMode}>");
PropertyMap map = new PropertyMap();
map.Add(ImageVisualProperty.LoopingMode, new PropertyValue((int)currentStates.loopMode));
- DoAction(ImageView.Property.IMAGE, Interop.Visual.GetActionUpdateProperty(), new PropertyValue(map));
+ DoAction(ImageView.Property.IMAGE, ActionUpdateProperty, new PropertyValue(map));
}
get
{
NUILog.Debug($"<[{GetId()}]SET currentStates.loopCount={currentStates.loopCount}>");
PropertyMap map = new PropertyMap();
map.Add(ImageVisualProperty.LoopCount, new PropertyValue(currentStates.loopCount));
- DoAction(ImageView.Property.IMAGE, Interop.Visual.GetActionUpdateProperty(), new PropertyValue(map));
+ DoAction(ImageView.Property.IMAGE, ActionUpdateProperty, new PropertyValue(map));
}
get
{
NUILog.Debug($"<[{GetId()}]SET val={currentStates.stopEndAction}>");
PropertyMap map = new PropertyMap();
map.Add(ImageVisualProperty.StopBehavior, new PropertyValue((int)currentStates.stopEndAction));
- DoAction(ImageView.Property.IMAGE, Interop.Visual.GetActionUpdateProperty(), new PropertyValue(map));
+ DoAction(ImageView.Property.IMAGE, ActionUpdateProperty, new PropertyValue(map));
}
get
{
NUILog.Debug($"<[{GetId()}]SET currentStates.redrawInScalingDown={currentStates.redrawInScalingDown}>");
PropertyMap map = new PropertyMap();
map.Add(ImageVisualProperty.RedrawInScalingDown, new PropertyValue(currentStates.redrawInScalingDown));
- DoAction(ImageView.Property.IMAGE, Interop.Visual.GetActionUpdateProperty(), new PropertyValue(map));
+ DoAction(ImageView.Property.IMAGE, ActionUpdateProperty, new PropertyValue(map));
}
get
{
PropertyMap map = new PropertyMap();
map.Add(ImageVisualProperty.PlayRange, new PropertyValue(array));
- DoAction(ImageView.Property.IMAGE, Interop.Visual.GetActionUpdateProperty(), new PropertyValue(map));
+ DoAction(ImageView.Property.IMAGE, ActionUpdateProperty, new PropertyValue(map));
NUILog.Debug($" [{GetId()}] currentStates.min:({currentStates.framePlayRangeMin}, max:{currentStates.framePlayRangeMax})>");
}
PropertyMap map = new PropertyMap();
map.Add(ImageVisualProperty.PlayRange, new PropertyValue(array));
- DoAction(ImageView.Property.IMAGE, Interop.Visual.GetActionUpdateProperty(), new PropertyValue(map));
+ DoAction(ImageView.Property.IMAGE, ActionUpdateProperty, new PropertyValue(map));
NUILog.Debug($" [{GetId()}] currentStates.mark1:{currentStates.mark1}, mark2:{currentStates.mark2} >");
}
/// See <see cref="Tizen.NUI.BaseComponents.TextField.SetInputFilter"/>, <see cref="Tizen.NUI.BaseComponents.TextField.GetInputFilter"/>, <see cref="Tizen.NUI.BaseComponents.TextEditor.SetInputFilter"/> and <see cref="Tizen.NUI.BaseComponents.TextEditor.GetInputFilter"/>. <br />
/// </remarks>
/// <since_tizen> 9 </since_tizen>
- public struct InputFilter
+ public struct InputFilter : IEquatable<InputFilter>
{
/// <summary>
/// A regular expression in the set of characters to be accepted by the inputFilter.
/// A regular expression in the set of characters to be rejected by the inputFilter.
/// </summary>
public string Rejected { get; set; }
- }
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="obj">The object to compare with the current object.</param>
+ /// <returns>true if equal InputFilter, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is InputFilter other && this.Equals(other);
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="other">The InputFilter to compare with the current InputFilter.</param>
+ /// <returns>true if equal InputFilter, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public bool Equals(InputFilter other) => Accepted == other.Accepted && Rejected == other.Rejected;
+
+ /// <summary>
+ /// The == operator.
+ /// </summary>
+ /// <param name="lhsInputFilter">InputFilter to compare</param>
+ /// <param name="rhsInputFilter">InputFilter to be compared</param>
+ /// <returns>true if InputFilters are equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator ==(InputFilter lhsInputFilter, InputFilter rhsInputFilter) => lhsInputFilter.Equals(rhsInputFilter);
+
+ /// <summary>
+ /// The != operator.
+ /// </summary>
+ /// <param name="lhsInputFilter">InputFilter to compare</param>
+ /// <param name="rhsInputFilter">InputFilter to be compared</param>
+ /// <returns>true if InputFilters are not equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator !=(InputFilter lhsInputFilter, InputFilter rhsInputFilter) => !lhsInputFilter.Equals(rhsInputFilter);
+
+ /// <summary>
+ /// Gets the hash code of this InputFilter.
+ /// </summary>
+ /// <returns>The hash code.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => (Accepted, Rejected).GetHashCode();
+ }
/// <summary>
/// A struct to pass data of Strikethrough PropertyMap. <br />
/// See <see cref="Tizen.NUI.BaseComponents.TextLabel.SetStrikethrough"/>, <see cref="Tizen.NUI.BaseComponents.TextLabel.GetStrikethrough"/>, <see cref="Tizen.NUI.BaseComponents.TextField.SetStrikethrough"/>, <see cref="Tizen.NUI.BaseComponents.TextField.GetStrikethrough"/>, <see cref="Tizen.NUI.BaseComponents.TextEditor.SetStrikethrough"/> and <see cref="Tizen.NUI.BaseComponents.TextEditor.GetStrikethrough"/>. <br />
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1815: Override equals and operator equals on value types")]
- public struct Strikethrough
+ public struct Strikethrough : IEquatable<Strikethrough>
{
/// <summary>
/// Whether the strikethrough is enabled (the default value is false).
[EditorBrowsable(EditorBrowsableState.Never)]
public float? Height { get; set; }
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="obj">The object to compare with the current object.</param>
+ /// <returns>true if equal Strikethrough, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is Strikethrough other && this.Equals(other);
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="other">The Strikethrough to compare with the current Strikethrough.</param>
+ /// <returns>true if equal Strikethrough, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public bool Equals(Strikethrough other) => Enable == other.Enable && Color == other.Color && Height == other.Height;
+
+ /// <summary>
+ /// The == operator.
+ /// </summary>
+ /// <param name="lhsStrikethrough">Strikethrough to compare</param>
+ /// <param name="rhsStrikethrough">Strikethrough to be compared</param>
+ /// <returns>true if Strikethroughs are equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator ==(Strikethrough lhsStrikethrough, Strikethrough rhsStrikethrough) => lhsStrikethrough.Equals(rhsStrikethrough);
+
+ /// <summary>
+ /// The != operator.
+ /// </summary>
+ /// <param name="lhsStrikethrough">Strikethrough to compare</param>
+ /// <param name="rhsStrikethrough">Strikethrough to be compared</param>
+ /// <returns>true if Strikethroughs are not equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator !=(Strikethrough lhsStrikethrough, Strikethrough rhsStrikethrough) => !lhsStrikethrough.Equals(rhsStrikethrough);
+
+ /// <summary>
+ /// Gets the hash code of this Strikethrough.
+ /// </summary>
+ /// <returns>The hash code.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => (Enable, Color, Height).GetHashCode();
}
/// <summary>
/// See <see cref="Tizen.NUI.BaseComponents.TextLabel.SetFontStyle"/>, <see cref="Tizen.NUI.BaseComponents.TextLabel.GetFontStyle"/>, <see cref="Tizen.NUI.BaseComponents.TextField.SetFontStyle"/>, <see cref="Tizen.NUI.BaseComponents.TextField.GetFontStyle"/>, <see cref="Tizen.NUI.BaseComponents.TextEditor.SetFontStyle"/> and <see cref="Tizen.NUI.BaseComponents.TextEditor.GetFontStyle"/>. <br />
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
- public struct FontStyle
+ public struct FontStyle : IEquatable<FontStyle>
{
/// <summary>
/// The Width defines occupied by each glyph.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public FontSlantType Slant { get; set; }
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="obj">The object to compare with the current object.</param>
+ /// <returns>true if equal FontStyle, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is FontStyle other && this.Equals(other);
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="other">The FontStyle to compare with the current FontStyle.</param>
+ /// <returns>true if equal FontStyle, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public bool Equals(FontStyle other) => Width == other.Width && Weight == other.Weight && Slant == other.Slant;
+
+ /// <summary>
+ /// The == operator.
+ /// </summary>
+ /// <param name="lhsFontStyle">FontStyle to compare</param>
+ /// <param name="rhsFontStyle">FontStyle to be compared</param>
+ /// <returns>true if FontStyles are equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator ==(FontStyle lhsFontStyle, FontStyle rhsFontStyle) => lhsFontStyle.Equals(rhsFontStyle);
+
+ /// <summary>
+ /// The != operator.
+ /// </summary>
+ /// <param name="lhsFontStyle">FontStyle to compare</param>
+ /// <param name="rhsFontStyle">FontStyle to be compared</param>
+ /// <returns>true if FontStyles are not equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator !=(FontStyle lhsFontStyle, FontStyle rhsFontStyle) => !lhsFontStyle.Equals(rhsFontStyle);
+
+ /// <summary>
+ /// Gets the hash code of this FontStyle.
+ /// </summary>
+ /// <returns>The hash code.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => (Width, Weight, Slant).GetHashCode();
}
/// <summary>
/// See <see cref="Tizen.NUI.BaseComponents.TextLabel.SetUnderline"/>, <see cref="Tizen.NUI.BaseComponents.TextLabel.GetUnderline"/>, <see cref="Tizen.NUI.BaseComponents.TextField.SetUnderline"/>, <see cref="Tizen.NUI.BaseComponents.TextField.GetUnderline"/>, <see cref="Tizen.NUI.BaseComponents.TextEditor.SetUnderline"/> and <see cref="Tizen.NUI.BaseComponents.TextEditor.GetUnderline"/>. <br />
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
- public struct Underline
+ public struct Underline : IEquatable<Underline>
{
/// <summary>
/// Whether the underline is enabled (the default value is false).
public bool Enable { get; set; }
/// <summary>
+ /// The type of the underline (the default type is Solid).
+ /// </summary>
+ public UnderlineType Type { get; set; }
+
+ /// <summary>
/// The color of the underline (if not provided then the color of the text is used).
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public float? Height { get; set; }
+
+ /// <summary>
+ /// The width of the dashes of the dashed underline (if null, the default value is 2.0f). <br />
+ /// Only valid when "UnderlineType.Dashed" type is used.
+ /// </summary>
+ public float? DashWidth { get; set; }
+
+ /// <summary>
+ /// The gap between the dashes of the dashed underline (if null, the default value is 1.0f). <br />
+ /// Only valid when "UnderlineType.Dashed" type is used.
+ /// </summary>
+ public float? DashGap { get; set; }
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="obj">The object to compare with the current object.</param>
+ /// <returns>true if equal Underline, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is Underline other && this.Equals(other);
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="other">The Underline to compare with the current Underline.</param>
+ /// <returns>true if equal Underline, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public bool Equals(Underline other) => Enable == other.Enable && Color == other.Color && Height == other.Height;
+
+ /// <summary>
+ /// The == operator.
+ /// </summary>
+ /// <param name="lhsUnderline">Underline to compare</param>
+ /// <param name="rhsUnderline">Underline to be compared</param>
+ /// <returns>true if Underlines are equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator ==(Underline lhsUnderline, Underline rhsUnderline) => lhsUnderline.Equals(rhsUnderline);
+
+ /// <summary>
+ /// The != operator.
+ /// </summary>
+ /// <param name="lhsUnderline">Underline to compare</param>
+ /// <param name="rhsUnderline">Underline to be compared</param>
+ /// <returns>true if Underlines are not equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator !=(Underline lhsUnderline, Underline rhsUnderline) => !lhsUnderline.Equals(rhsUnderline);
+
+ /// <summary>
+ /// Gets the hash code of this Underline.
+ /// </summary>
+ /// <returns>The hash code.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => (Enable, Color, Height).GetHashCode();
}
/// <summary>
/// See <see cref="Tizen.NUI.BaseComponents.TextLabel.SetShadow"/>, <see cref="Tizen.NUI.BaseComponents.TextLabel.GetShadow"/>, <see cref="Tizen.NUI.BaseComponents.TextField.SetShadow"/>, <see cref="Tizen.NUI.BaseComponents.TextField.GetShadow"/>, <see cref="Tizen.NUI.BaseComponents.TextEditor.SetShadow"/> and <see cref="Tizen.NUI.BaseComponents.TextEditor.GetShadow"/>. <br />
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
- public struct Shadow
+ public struct Shadow : IEquatable<Shadow>
{
/// <summary>
/// The color of the shadow (the default color is Color.Black).
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public float? BlurRadius { get; set; }
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="obj">The object to compare with the current object.</param>
+ /// <returns>true if equal Shadow, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is Shadow other && this.Equals(other);
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="other">The Shadow to compare with the current Shadow.</param>
+ /// <returns>true if equal Shadow, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public bool Equals(Shadow other) => Color == other.Color && Offset == other.Offset && BlurRadius == other.BlurRadius;
+
+ /// <summary>
+ /// The == operator.
+ /// </summary>
+ /// <param name="lhsShadow">Shadow to compare</param>
+ /// <param name="rhsShadow">Shadow to be compared</param>
+ /// <returns>true if Shadows are equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator ==(Shadow lhsShadow, Shadow rhsShadow) => lhsShadow.Equals(rhsShadow);
+
+ /// <summary>
+ /// The != operator.
+ /// </summary>
+ /// <param name="lhsShadow">Shadow to compare</param>
+ /// <param name="rhsShadow">Shadow to be compared</param>
+ /// <returns>true if Shadows are not equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator !=(Shadow lhsShadow, Shadow rhsShadow) => !lhsShadow.Equals(rhsShadow);
+
+ /// <summary>
+ /// Gets the hash code of this Shadow.
+ /// </summary>
+ /// <returns>The hash code.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => (Color, Offset, BlurRadius).GetHashCode();
}
/// <summary>
/// See <see cref="Tizen.NUI.BaseComponents.TextLabel.SetOutline"/>, <see cref="Tizen.NUI.BaseComponents.TextLabel.GetOutline"/>, <see cref="Tizen.NUI.BaseComponents.TextField.SetOutline"/>, <see cref="Tizen.NUI.BaseComponents.TextField.GetOutline"/>, <see cref="Tizen.NUI.BaseComponents.TextEditor.SetOutline"/> and <see cref="Tizen.NUI.BaseComponents.TextEditor.GetOutline"/>. <br />
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
- public struct Outline
+ public struct Outline : IEquatable<Outline>
{
/// <summary>
/// The color of the outline (the default color is Color.White).
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public float? Width { get; set; }
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="obj">The object to compare with the current object.</param>
+ /// <returns>true if equal Outline, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is Outline other && this.Equals(other);
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="other">The Outline to compare with the current Outline.</param>
+ /// <returns>true if equal Outline, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public bool Equals(Outline other) => Color == other.Color && Width == other.Width;
+
+ /// <summary>
+ /// The == operator.
+ /// </summary>
+ /// <param name="lhsOutline">Outline to compare</param>
+ /// <param name="rhsOutline">Outline to be compared</param>
+ /// <returns>true if Outlines are equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator ==(Outline lhsOutline, Outline rhsOutline) => lhsOutline.Equals(rhsOutline);
+
+ /// <summary>
+ /// The != operator.
+ /// </summary>
+ /// <param name="lhsOutline">Outline to compare</param>
+ /// <param name="rhsOutline">Outline to be compared</param>
+ /// <returns>true if Outlines are not equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator !=(Outline lhsOutline, Outline rhsOutline) => !lhsOutline.Equals(rhsOutline);
+
+ /// <summary>
+ /// Gets the hash code of this Outline.
+ /// </summary>
+ /// <returns>The hash code.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => (Color, Width).GetHashCode();
}
/// <summary>
/// See <see cref="Tizen.NUI.BaseComponents.TextLabel.SetTextFit"/> and <see cref="Tizen.NUI.BaseComponents.TextLabel.GetTextFit"/>. <br />
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
- public struct TextFit
+ public struct TextFit : IEquatable<TextFit>
{
/// <summary>
/// True to enable the text fit or false to disable (the default value is false).
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public float? FontSize { get; set; }
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="obj">The object to compare with the current object.</param>
+ /// <returns>true if equal TextFit, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is TextFit other && this.Equals(other);
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="other">The TextFit to compare with the current TextFit.</param>
+ /// <returns>true if equal TextFit, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public bool Equals(TextFit other) => Enable == other.Enable && MinSize == other.MinSize && MaxSize == other.MaxSize &&
+ StepSize == other.StepSize && FontSizeType == other.FontSizeType && FontSize == other.FontSize;
+
+ /// <summary>
+ /// The == operator.
+ /// </summary>
+ /// <param name="lhsTextFit">TextFit to compare</param>
+ /// <param name="rhsTextFit">TextFit to be compared</param>
+ /// <returns>true if TextFits are equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator ==(TextFit lhsTextFit, TextFit rhsTextFit) => lhsTextFit.Equals(rhsTextFit);
+
+ /// <summary>
+ /// The != operator.
+ /// </summary>
+ /// <param name="lhsTextFit">TextFit to compare</param>
+ /// <param name="rhsTextFit">TextFit to be compared</param>
+ /// <returns>true if TextFits are not equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator !=(TextFit lhsTextFit, TextFit rhsTextFit) => !lhsTextFit.Equals(rhsTextFit);
+
+ /// <summary>
+ /// Gets the hash code of this TextFit.
+ /// </summary>
+ /// <returns>The hash code.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => (Enable, MinSize, MaxSize, StepSize, FontSizeType, FontSize).GetHashCode();
}
/// <summary>
/// See <see cref="Tizen.NUI.BaseComponents.TextField.SetPlaceholder"/>, <see cref="Tizen.NUI.BaseComponents.TextField.SetPlaceholder"/>, <see cref="Tizen.NUI.BaseComponents.TextEditor.SetPlaceholder"/> and <see cref="Tizen.NUI.BaseComponents.TextEditor.SetPlaceholder"/>. <br />
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
- public struct Placeholder
+ public struct Placeholder : IEquatable<Placeholder>
{
/// <summary>
/// The text to display when the TextField is empty and inactive.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool Ellipsis { get; set; }
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="obj">The object to compare with the current object.</param>
+ /// <returns>true if equal Placeholder, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is Placeholder other && this.Equals(other);
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="other">The Placeholder to compare with the current Placeholder.</param>
+ /// <returns>true if equal Placeholder, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public bool Equals(Placeholder other) =>
+ Text == other.Text && TextFocused == other.TextFocused && Color == other.Color && FontFamily == other.FontFamily &&
+ FontStyle == other.FontStyle && PointSize == other.PointSize && PixelSize == other.PixelSize && Ellipsis == other.Ellipsis;
+
+ /// <summary>
+ /// The == operator.
+ /// </summary>
+ /// <param name="lhsPlaceholder">Placeholder to compare</param>
+ /// <param name="rhsPlaceholder">Placeholder to be compared</param>
+ /// <returns>true if Placeholders are equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator ==(Placeholder lhsPlaceholder, Placeholder rhsPlaceholder) => lhsPlaceholder.Equals(rhsPlaceholder);
+
+ /// <summary>
+ /// The != operator.
+ /// </summary>
+ /// <param name="lhsPlaceholder">Placeholder to compare</param>
+ /// <param name="rhsPlaceholder">Placeholder to be compared</param>
+ /// <returns>true if Placeholders are not equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator !=(Placeholder lhsPlaceholder, Placeholder rhsPlaceholder) => !lhsPlaceholder.Equals(rhsPlaceholder);
+
+ /// <summary>
+ /// Gets the hash code of this Placeholder.
+ /// </summary>
+ /// <returns>The hash code.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => (Text, TextFocused, Color, FontFamily, FontStyle, PointSize, PixelSize, Ellipsis).GetHashCode();
}
/// <summary>
/// See <see cref="Tizen.NUI.BaseComponents.TextField.SetHiddenInput"/> and <see cref="Tizen.NUI.BaseComponents.TextField.GetHiddenInput"/>. <br />
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
- public struct HiddenInput
+ public struct HiddenInput : IEquatable<HiddenInput>
{
/// <summary>
/// The mode for input text display. <br />
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public int? ShowLastCharacterDuration { get; set; }
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="obj">The object to compare with the current object.</param>
+ /// <returns>true if equal HiddenInput, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is HiddenInput other && this.Equals(other);
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="other">The HiddenInput to compare with the current HiddenInput.</param>
+ /// <returns>true if equal HiddenInput, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public bool Equals(HiddenInput other) => Mode == other.Mode && SubstituteCharacter == other.SubstituteCharacter &&
+ SubstituteCount == other.SubstituteCount && ShowLastCharacterDuration == other.ShowLastCharacterDuration;
+
+ /// <summary>
+ /// The == operator.
+ /// </summary>
+ /// <param name="lhsHiddenInput">HiddenInput to compare</param>
+ /// <param name="rhsHiddenInput">HiddenInput to be compared</param>
+ /// <returns>true if HiddenInputs are equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator ==(HiddenInput lhsHiddenInput, HiddenInput rhsHiddenInput) => lhsHiddenInput.Equals(rhsHiddenInput);
+
+ /// <summary>
+ /// The != operator.
+ /// </summary>
+ /// <param name="lhsHiddenInput">HiddenInput to compare</param>
+ /// <param name="rhsHiddenInput">HiddenInput to be compared</param>
+ /// <returns>true if HiddenInputs are not equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator !=(HiddenInput lhsHiddenInput, HiddenInput rhsHiddenInput) => !lhsHiddenInput.Equals(rhsHiddenInput);
+
+ /// <summary>
+ /// Gets the hash code of this HiddenInput.
+ /// </summary>
+ /// <returns>The hash code.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => (Mode, SubstituteCharacter, SubstituteCount, ShowLastCharacterDuration).GetHashCode();
}
/// <summary>
/// <see cref="Tizen.NUI.BaseComponents.TextEditor.SetSelectionHandleImage"/>, <see cref="Tizen.NUI.BaseComponents.TextEditor.GetSelectionHandleImage"/>, <see cref="Tizen.NUI.BaseComponents.TextEditor.SetSelectionHandlePressedImage"/>, <see cref="Tizen.NUI.BaseComponents.TextEditor.GetSelectionHandlePressedImage"/>, <see cref="Tizen.NUI.BaseComponents.TextEditor.SetSelectionHandleMarkerImage"/> and <see cref="Tizen.NUI.BaseComponents.TextEditor.GetSelectionHandleMarkerImage"/>. <br />
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
- public struct SelectionHandleImage
+ public struct SelectionHandleImage : IEquatable<SelectionHandleImage>
{
/// <summary>
/// The image path to display for the left selection handle. <br />
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public string RightImageUrl { get; set; }
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="obj">The object to compare with the current object.</param>
+ /// <returns>true if equal SelectionHandleImage, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj) => obj is SelectionHandleImage other && this.Equals(other);
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ /// <param name="other">The SelectionHandleImage to compare with the current SelectionHandleImage.</param>
+ /// <returns>true if equal SelectionHandleImage, else false.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public bool Equals(SelectionHandleImage other) => LeftImageUrl == other.LeftImageUrl && RightImageUrl == other.RightImageUrl;
+
+ /// <summary>
+ /// The == operator.
+ /// </summary>
+ /// <param name="lhsSelectionHandleImage">SelectionHandleImage to compare</param>
+ /// <param name="rhsSelectionHandleImage">SelectionHandleImage to be compared</param>
+ /// <returns>true if SelectionHandleImages are equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator ==(SelectionHandleImage lhsSelectionHandleImage, SelectionHandleImage rhsSelectionHandleImage)
+ => lhsSelectionHandleImage.Equals(rhsSelectionHandleImage);
+
+ /// <summary>
+ /// The != operator.
+ /// </summary>
+ /// <param name="lhsSelectionHandleImage">SelectionHandleImage to compare</param>
+ /// <param name="rhsSelectionHandleImage">SelectionHandleImage to be compared</param>
+ /// <returns>true if SelectionHandleImages are not equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator !=(SelectionHandleImage lhsSelectionHandleImage, SelectionHandleImage rhsSelectionHandleImage)
+ => !lhsSelectionHandleImage.Equals(rhsSelectionHandleImage);
+
+ /// <summary>
+ /// Gets the hash code of this SelectionHandleImage.
+ /// </summary>
+ /// <returns>The hash code.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => (LeftImageUrl, RightImageUrl).GetHashCode();
}
-}
\ No newline at end of file
+}
var map = new PropertyMap();
map.Add("enable", underline.Enable);
+ map.Add("type", (int)underline.Type);
if (underline.Color != null)
map.Add("color", underline.Color);
if (underline.Height != null)
map.Add("height", (float)underline.Height);
+
+ if (underline.DashWidth != null)
+ map.Add("dashWidth", (float)underline.DashWidth);
+
+ if (underline.DashGap != null)
+ map.Add("dashGap", (float)underline.DashGap);
return map;
}
if (null != map)
{
underline.Enable = GetBoolFromMap(map, "enable", false);
+ underline.Type = (UnderlineType)GetIntFromMap(map, "type", 0);
underline.Color = GetColorFromMap(map, "color");
underline.Height = GetFloatFromMap(map, "height", 0.0f);
+ underline.DashWidth = GetNullableFloatFromMap(map, "dashWidth");
+ underline.DashGap = GetNullableFloatFromMap(map, "dashGap");
}
return underline;
return value;
}
+ internal static int GetIntFromMap(PropertyMap map, string key, int defaultValue)
+ {
+ int value = defaultValue;
+ using (var propertyValue = map.Find(0, key))
+ {
+ if (null != propertyValue) propertyValue.Get(out value);
+ }
+ return value;
+ }
+
internal static float GetFloatFromMap(PropertyMap map, string key, float defaultValue)
{
float value = defaultValue;
}
}
+ internal static float? GetNullableFloatFromMap(PropertyMap map, string key)
+ {
+ using (var propertyValue = map.Find(0, key))
+ {
+ if (propertyValue == null)
+ return null;
+
+ propertyValue.Get(out float value);
+ return value;
+ }
+ }
+
internal static bool IsValue(PropertyMap map, int key)
{
using (var propertyValue = map.Find(key))
{
get
{
- using (View view = Accessibility.Accessibility.Instance.GetCurrentlyHighlightedView())
- {
- return view == this;
- }
+ return (this == Accessibility.Accessibility.Instance.GetCurrentlyHighlightedView());
}
}
InsertText = (startPosition, text) => AccessibilityInsertText(startPosition, Marshal.PtrToStringAnsi(text)),
SetTextContents = (newContents) => AccessibilitySetTextContents(Marshal.PtrToStringAnsi(newContents)),
DeleteText = (startPosition, endPosition) => AccessibilityDeleteText(startPosition, endPosition),
- ScrollToChild = (child) => {
- using (var view = new View(child, true))
- {
- return AccessibilityScrollToChild(view);
- }
- },
+ ScrollToChild = (child) => AccessibilityScrollToChild(this.GetInstanceSafely<View>(child)),
GetSelectedChildrenCount = () => AccessibilityGetSelectedChildrenCount(),
GetSelectedChild = (selectedChildIndex) => View.getCPtr(AccessibilityGetSelectedChild(selectedChildIndex)).Handle,
SelectChild = (childIndex) => AccessibilitySelectChild(childIndex),
{
//throw new System.InvalidOperationException("You have deleted a view that is not a child of this view.");
Tizen.Log.Error("NUI", "You have deleted a view that is not a child of this view.");
+ return;
}
bool hasLayout = (layout != null);
public static readonly Color YellowGreen = NDalic.YELLOW_GREEN;
- private readonly bool hashDummy;
-
/// <summary>
/// Default constructor
/// </summary>
internal Color(global::System.IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn)
{
- hashDummy = false;
}
internal Color(ColorChangedCallback cb, float r, float g, float b, float a) : this(Interop.Vector4.NewVector4(ValueCheck(r), ValueCheck(g), ValueCheck(b), ValueCheck(a)), true)
return equal;
}
+ /// <summary>
+ /// The == operator.
+ /// </summary>
+ /// <param name="arg1">Color to compare</param>
+ /// <param name="arg2">Color to be compared</param>
+ /// <returns>true if Colors are equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator ==(Color arg1, Color arg2)
+ {
+ if (arg1 is null)
+ {
+ if (arg2 is null)
+ return true;
+
+ return false;
+ }
+
+ return arg1.Equals(arg2);
+ }
+
+ /// <summary>
+ /// The != operator.
+ /// </summary>
+ /// <param name="arg1">Color to compare</param>
+ /// <param name="arg2">Color to be compared</param>
+ /// <returns>true if Colors are not equal</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static bool operator !=(Color arg1, Color arg2) => !(arg1 == arg2);
+
/// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
- return hashDummy.GetHashCode();
+ return base.GetHashCode();
}
private float ValueOfIndex(uint index)
/*
- * Copyright(c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright(c) 2022 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
throw new ArgumentNullException(nameof(child));
}
+ if (child.GetParent() == null) // Early out if child parent is null.
+ return;
+
+ if (child.GetParent() != this)
+ {
+ //throw new System.InvalidOperationException("You have deleted a view that is not a child of this layer.");
+ Tizen.Log.Error("NUI", "You have deleted a view that is not a child of this layer.");
+ return;
+ }
Interop.Actor.Remove(SwigCPtr, View.getCPtr(child));
if (NDalicPINVOKE.SWIGPendingException.Pending)
throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
/// <summary>
+ /// Enumeration for the type of Underline.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public enum UnderlineType
+ {
+ /// <summary>
+ /// The default underline type.
+ /// </summary>
+ Solid,
+
+ /// <summary>
+ /// The dashed underline type.
+ /// </summary>
+ Dashed,
+
+ /// <summary>
+ /// The double underline type.
+ /// </summary>
+ Double
+ }
+
+ /// <summary>
/// Enumeration for the size type of font. <br />
/// </summary>
/// <remarks>
--- /dev/null
+{
+ // Use IntelliSense to learn about possible attributes.
+ // Hover to view descriptions of existing attributes.
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": ".NET Core Launch (console)",
+ "type": "coreclr",
+ "request": "launch",
+ "preLaunchTask": "build",
+ "program": "${workspaceFolder}/bin/Debug/netcoreapp3.1/Tizen.NUI.Devel.Tests.dll",
+ "args": [],
+ "env": {
+ "DESKTOP_PREFIX":"/home/{should be fixed}/dali-env/opt",
+ "PATH":"/home/{should be fixed}/dali-env/opt/bin:$PATH",
+ "LD_LIBRARY_PATH":"/home/{should be fixed}/dali-env/opt/lib:$LD_LIBRARY_PATH",
+ "INCLUDEDIR":"/home/{should be fixed}/dali-env/opt/include",
+ "PKG_CONFIG_PATH":"/home/{should be fixed}/dali-env/opt/lib/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig",
+ "DOTNET_CLI_TELEMETRY_OPTOUT":"1",
+ "DALI_WINDOW_WIDTH":"720",
+ "DALI_WINDOW_HEIGHT":"1080",
+ },
+ "cwd": "${workspaceFolder}",
+ "console": "internalConsole",
+ "stopAtEntry": false
+ },
+ {
+ "name": ".NET Core Attach",
+ "type": "coreclr",
+ "request": "attach"
+ }
+ ]
+}
--- /dev/null
+{
+ "version": "2.0.0",
+ "tasks": [
+ {
+ "label": "build",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "build",
+ "${workspaceFolder}/Tizen.NUI.Devel.Tests.csproj",
+ "/property:GenerateFullPaths=true",
+ "/consoleloggerparameters:NoSummary"
+ ],
+ "problemMatcher": "$msCompile"
+ },
+ {
+ "label": "publish",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "publish",
+ "${workspaceFolder}/Tizen.NUI.Devel.Tests.csproj",
+ "/property:GenerateFullPaths=true",
+ "/consoleloggerparameters:NoSummary"
+ ],
+ "problemMatcher": "$msCompile"
+ },
+ {
+ "label": "watch",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "watch",
+ "run",
+ "${workspaceFolder}/Tizen.NUI.Devel.Tests.csproj",
+ "/property:GenerateFullPaths=true",
+ "/consoleloggerparameters:NoSummary"
+ ],
+ "problemMatcher": "$msCompile"
+ }
+ ]
+}
\ No newline at end of file
--- /dev/null
+using Tizen.NUI.Binding.Internals;
+using Tizen.NUI.Devel.Tests;
+using Tizen.NUI.Xaml;
+
+[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+using System;
+using NUnitLite.TUnit;
+using Tizen.Applications;
+using Tizen.NUI;
+using Tizen.NUI.BaseComponents;
+using System.Threading;
+using System.Diagnostics;
+using System.Threading.Tasks;
+
+namespace Tizen.NUI.Devel.Tests
+{
+ using tlog = Tizen.Log;
+ public class App : Tizen.NUI.NUIApplication
+ {
+ static string tag = "NUITEST";
+
+ public App() : base()
+ {
+ tlog.Debug(tag, "Call App()");
+ }
+
+ View root;
+ public static TextLabel mainTitle;
+ static string title = "NUI Auto TCT \n\n";
+ float textSize = 30.0f;
+ Window window;
+ Layer layer;
+ public static int mainPid;
+ public static int mainTid;
+ Timer timer;
+
+ protected override void OnCreate()
+ {
+ base.OnCreate();
+
+ tlog.Debug(tag, "OnCreate() START!");
+
+ mainPid = Process.GetCurrentProcess().Id;
+ mainTid = Thread.CurrentThread.ManagedThreadId;
+
+ window = NUIApplication.GetDefaultWindow();
+ window.BackgroundColor = Color.Green;
+
+ root = new View()
+ {
+ Size = new Size(100, 100),
+ BackgroundColor = Color.White,
+ PositionUsesPivotPoint = true,
+ ParentOrigin = ParentOrigin.Center,
+ PivotPoint = PivotPoint.Center,
+ };
+
+ layer = window.GetDefaultLayer();
+ layer.Add(root);
+
+ mainTitle = new TextLabel()
+ {
+ MultiLine = true,
+ Text = title + $"Process ID: {Process.GetCurrentProcess().Id} \nThread ID: {Thread.CurrentThread.ManagedThreadId}\n",
+ PixelSize = textSize,
+ BackgroundColor = Color.Cyan,
+ Size = new Size(window.WindowSize.Width * 0.9f, window.WindowSize.Height * 0.9f, 0),
+ PositionUsesPivotPoint = true,
+ ParentOrigin = ParentOrigin.Center,
+ PivotPoint = PivotPoint.Center,
+ };
+ root.Add(mainTitle);
+
+ tlog.Debug(tag, "OnCreate() END!");
+
+ timer = new Timer(1000);
+ timer.Tick += OnTick;
+ timer.Start();
+
+ }
+
+ private bool OnTick(object obj, EventArgs e)
+ {
+ TRunner t = new TRunner();
+ t.LoadTestsuite();
+ t.Execute();
+
+ App.MainTitleChangeText("Finished!");
+ return false;
+ }
+
+
+
+ static public async Task MainTitleChangeBackgroundColor(Color color)
+ {
+ if (color != null)
+ {
+ mainTitle.BackgroundColor = color;
+ await Task.Delay(900);
+ }
+ }
+
+ static public async Task MainTitleChangeText(string tcTitle)
+ {
+ if (tcTitle != null)
+ {
+ var processId = Process.GetCurrentProcess().Id;
+ var threadId = Thread.CurrentThread.ManagedThreadId;
+
+ mainTitle.Text = $"{title}\nProcess ID: {processId}\nThread ID: {threadId}\n TC: {tcTitle}";
+ await Task.Delay(20);
+
+ tlog.Debug(tag, $"{title}\nProcess ID: {processId}\nThread ID: {threadId}\n TC: {tcTitle}");
+ }
+ }
+
+ protected override void OnAppControlReceived(AppControlReceivedEventArgs e)
+ {
+ base.OnAppControlReceived(e);
+ tlog.Debug(tag, $"### OnAppControlReceived() START!");
+ }
+
+ protected override void OnResume()
+ {
+ base.OnResume();
+
+ tlog.Debug(tag, $"### OnResume() START!");
+
+ // TRunner t = new TRunner();
+ // t.LoadTestsuite();
+ // t.Execute();
+
+ tlog.Debug(tag, $"OnResume() END!");
+ }
+
+ protected override void OnPause()
+ {
+ base.OnPause();
+ }
+
+ protected override void OnTerminate()
+ {
+ timer.Tick -= OnTick;
+ mainTitle.GetParent().Remove(mainTitle);
+ mainTitle = null;
+ root.GetParent().Remove(root);
+ root = null;
+
+ base.OnTerminate();
+ Exit();
+ }
+
+ static void Main(string[] args)
+ {
+ tlog.Debug(tag, "NUI RUN!");
+ App example = new App();
+ example.Run(args);
+ }
+ };
+}
--- /dev/null
+{
+ "folders": [
+ {
+ "path": "."
+ },
+ {
+ "path": "../nunitlite"
+ },
+ {
+ "path": "../nunit.framework"
+ },
+ {
+ "path": "../../../src/Tizen.NUI"
+ },
+ {
+ "path": "../../../src/Tizen.NUI.Components"
+ }
+ ],
+ "settings": {}
+}
--- /dev/null
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <!-- Property Group for .NET Core Project -->
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>netcoreapp3.1</TargetFramework>
+ <AssemblyName>Tizen.NUI.Devel.Tests</AssemblyName>
+ </PropertyGroup>
+
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugType>portable</DebugType>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>None</DebugType>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <Folder Include="lib\" />
+ </ItemGroup>
+
+ <!-- Include Nuget Package for Tizen Project building -->
+ <ItemGroup>
+ <ProjectReference Include="..\nunit.framework\nunit.framework.csproj" />
+ <ProjectReference Include="..\nunitlite\nunitlite.csproj" />
+ <ProjectReference Include="..\..\..\src\Tizen.NUI.Components\Tizen.NUI.Components.csproj" />
+ <ProjectReference Include="..\..\..\src\Tizen.NUI\Tizen.NUI.csproj" />
+ </ItemGroup>
+
+ <PropertyGroup>
+ <SignAssembly>true</SignAssembly>
+ <AssemblyOriginatorKeyFile>./NuiTest.snk</AssemblyOriginatorKeyFile>
+ <PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
+ </PropertyGroup>
+
+</Project>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?xml-stylesheet type="text/xsl" href="jgenhtml.xsl"?><coverage branch-rate="NaN" branches-covered="0" branches-valid="0" complexity="0" date="2021-05-27" filename="index" function-rate="0.092856176" functions-covered="685" functions-valid="7377" line-rate="0.14716579" lines-covered="5382" lines-valid="36571" testname="lcov.info" version="1.5">
+<sources>
+<source branches-hit="0" branches-valid="0" functions-hit="22" functions-valid="75" lines-hit="108" lines-valid="470" pathname="/public/Theme" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="21" lines-hit="0" lines-valid="55" pathname="/internal/Window" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="38" lines-hit="0" lines-valid="142" pathname="/internal/Transition" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="148" functions-valid="239" lines-hit="592" lines-valid="956" pathname="/internal/NativeBinding" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="8" functions-valid="81" lines-hit="16" lines-valid="185" pathname="/public/Application" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="9" lines-hit="0" lines-valid="19" pathname="/public/XamlBinding/Internals" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="42" functions-valid="176" lines-hit="162" lines-valid="786" pathname="/internal/Application" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="45" lines-hit="0" lines-valid="253" pathname="/internal/FrameBroker" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="223" lines-hit="0" lines-valid="1179" pathname="/internal/XamlBinding" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="32" lines-hit="0" lines-valid="307" pathname="/public/CustomView" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="167" lines-hit="0" lines-valid="465" pathname="/public/Accessibility" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="206" lines-hit="0" lines-valid="850" pathname="/public/Layouting" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="25" lines-hit="0" lines-valid="93" pathname="/internal/EXaml/Block" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="215" lines-hit="0" lines-valid="797" pathname="/public/Input" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="74" lines-hit="0" lines-valid="375" pathname="/public/Rendering" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="46" lines-hit="0" lines-valid="212" pathname="/public/ViewProperty" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="6" functions-valid="19" lines-hit="60" lines-valid="76" pathname="/internal/Interop" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="1" functions-valid="146" lines-hit="1" lines-valid="747" pathname="/public/Animation" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="17" lines-hit="0" lines-valid="75" pathname="/internal/XamlBinding/Interactivity" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="38" lines-hit="0" lines-valid="195" pathname="/internal/EXaml/Operation" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="59" lines-hit="0" lines-valid="269" pathname="/public/Xaml" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="11" lines-hit="0" lines-valid="106" pathname="/internal/EXaml" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="1" functions-valid="130" lines-hit="1" lines-valid="501" pathname="/public/Window" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="11" lines-hit="0" lines-valid="32" pathname="/internal/Animation" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="49" functions-valid="195" lines-hit="1060" lines-valid="1555" pathname="/public/BaseComponents/Style" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="32" lines-hit="0" lines-valid="195" pathname="/public/Images" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="59" lines-hit="0" lines-valid="316" pathname="/internal/EXaml/Action" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="8" lines-hit="0" lines-valid="15" pathname="/public/Transition" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="45" lines-hit="0" lines-valid="122" pathname="/public/Xaml/MarkupExtensions" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="59" functions-valid="1122" lines-hit="167" lines-valid="3602" pathname="/internal/Common" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="209" functions-valid="233" lines-hit="559" lines-valid="732" pathname="/public/Events" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="238" lines-hit="0" lines-valid="1994" pathname="/internal/Xaml" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="47" lines-hit="0" lines-valid="162" pathname="/public/XamlBinding/Interactivity" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="2" functions-valid="64" lines-hit="5" lines-valid="431" pathname="/internal/Layouting" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="386" lines-hit="0" lines-valid="1195" pathname="/internal/WebView" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="4" lines-hit="0" lines-valid="36" pathname="/public/EXaml" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="69" lines-hit="0" lines-valid="310" pathname="/public/Widget" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="19" lines-hit="0" lines-valid="75" pathname="/public/BaseComponents/VectorGraphics" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="24" lines-hit="0" lines-valid="63" pathname="/internal/Accessibility" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="11" lines-hit="0" lines-valid="38" pathname="/internal/FrameProvider" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="10" functions-valid="23" lines-hit="34" lines-valid="85" pathname="/public/Template" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="56" lines-hit="0" lines-valid="145" pathname="/internal/Widget" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="49" functions-valid="893" lines-hit="2207" lines-valid="7885" pathname="/public/BaseComponents" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="378" lines-hit="0" lines-valid="1448" pathname="/internal/Utility" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="244" lines-hit="0" lines-valid="1326" pathname="/public/Utility" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="66" functions-valid="720" lines-hit="369" lines-valid="3077" pathname="/public/Common" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="162" lines-hit="0" lines-valid="1167" pathname="/public/Visuals" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="0" functions-valid="5" lines-hit="0" lines-valid="22" pathname="/internal/XamlBinding/Internals" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+<source branches-hit="0" branches-valid="0" functions-hit="13" functions-valid="237" lines-hit="41" lines-valid="1430" pathname="/public/XamlBinding" prefix="/home/wanggw/LineCoverageTool/coverage/Tizensource/TizenFX/src/Tizen.NUI/src"/>
+</sources>
+<config branch-coverage="false" description-file="false" function-coverage="true" genhtml_hi_limit="90" genhtml_med_limit="75" legend="false" no-sort="false" no-source="false"/>
+</coverage>
--- /dev/null
+using global::System;
+using NUnit.Framework;
+using NUnit.Framework.TUnit;
+using Tizen.NUI.Components;
+using Tizen.NUI.BaseComponents;
+
+namespace Tizen.NUI.Devel.Tests
+{
+ using tlog = Tizen.Log;
+
+ [TestFixture]
+ [Description("public/BaseComponents/View")]
+ public class InternalViewTest
+ {
+ private const string tag = "NUITEST";
+ private const int testSize = 100;
+ private const int testPosition = 100;
+
+ [SetUp]
+ public void Init()
+ {
+ tlog.Info(tag, "Init() is called!");
+ }
+
+ [TearDown]
+ public void Destroy()
+ {
+ tlog.Info(tag, "Destroy() is called!");
+ }
+
+ [Test]
+ [Category("P1")]
+ [Description("internal API test in Ubuntu, View.ColorMode")]
+ [Property("SPEC", "Tizen.NUI.BaseComponents.View.ColorMode")]
+ [Property("SPEC_URL", "-")]
+ [Property("CRITERIA", "PRO")]
+ [Property("AUTHOR", "dongsug.song@samsung.com")]
+ public void ColorMode_CHECK_DEFAULT_VALUE()
+ {
+ /* TEST CODE */
+ View testView = new View();
+ var colormode = testView.ColorMode;
+
+ Assert.AreEqual(Tizen.NUI.ColorMode.UseOwnMultiplyParentAlpha, colormode, "colormode should be UseOwnMultiplyParentAlpha");
+
+ testView.Dispose();
+ }
+
+ [Test]
+ [Category("P1")]
+ [Description("internal API test in Ubuntu, View.ColorMode")]
+ [Property("SPEC", "Tizen.NUI.BaseComponents.View.ColorMode")]
+ [Property("SPEC_URL", "-")]
+ [Property("CRITERIA", "PRO")]
+ [Property("AUTHOR", "dongsug.song@samsung.com")]
+ public void ColorMode_CHECK_DEFAULT_VALUE_WITH_ADDED_VIEW()
+ {
+ /* TEST CODE */
+ View testView = new View()
+ {
+ Size = new Size(testSize, testSize, 0),
+ Position = new Position(testPosition, testPosition, 0),
+ BackgroundColor = Color.Red,
+ };
+ NUIApplication.GetDefaultWindow().Add(testView);
+
+ var colormode = testView.ColorMode;
+
+ Assert.AreEqual(Tizen.NUI.ColorMode.UseOwnMultiplyParentAlpha, colormode, "colormode should be UseOwnMultiplyParentAlpha");
+
+ testView.Unparent();
+ testView.Dispose();
+ }
+
+ [Test]
+ [Category("P1")]
+ [Description("internal API test in Ubuntu, View.ColorMode")]
+ [Property("SPEC", "Tizen.NUI.BaseComponents.View.ColorMode")]
+ [Property("SPEC_URL", "-")]
+ [Property("CRITERIA", "PRO")]
+ [Property("AUTHOR", "dongsug.song@samsung.com")]
+ public void ColorMode_SET_GET_VALUE()
+ {
+ /* TEST CODE */
+ View testView = new View();
+
+ testView.ColorMode = Tizen.NUI.ColorMode.UseOwnColor;
+ Assert.AreEqual(Tizen.NUI.ColorMode.UseOwnColor, testView.ColorMode, "colormode should be UseOwnColor");
+
+ testView.ColorMode = Tizen.NUI.ColorMode.UseParentColor;
+ Assert.AreEqual(Tizen.NUI.ColorMode.UseParentColor, testView.ColorMode, "colormode should be UseParentColor");
+
+ testView.ColorMode = Tizen.NUI.ColorMode.UseOwnMultiplyParentColor;
+ Assert.AreEqual(Tizen.NUI.ColorMode.UseOwnMultiplyParentColor, testView.ColorMode, "colormode should be UseOwnMultiplyParentColor");
+
+ testView.ColorMode = Tizen.NUI.ColorMode.UseOwnMultiplyParentAlpha;
+ Assert.AreEqual(Tizen.NUI.ColorMode.UseOwnMultiplyParentAlpha, testView.ColorMode, "colormode should be UseOwnMultiplyParentAlpha");
+
+ testView.Dispose();
+ }
+
+ [Test]
+ [Category("P1")]
+ [Description("internal API test in Ubuntu, View.ColorMode")]
+ [Property("SPEC", "Tizen.NUI.BaseComponents.View.ColorMode")]
+ [Property("SPEC_URL", "-")]
+ [Property("CRITERIA", "PRO")]
+ [Property("AUTHOR", "dongsug.song@samsung.com")]
+ public void ColorMode_SET_GET_VALUE_WITH_ADDED_VIEW()
+ {
+ /* TEST CODE */
+ View testView = new View()
+ {
+ Size = new Size(testSize, testSize, 0),
+ Position = new Position(testPosition, testPosition, 0),
+ BackgroundColor = Color.Red,
+ };
+ NUIApplication.GetDefaultWindow().Add(testView);
+
+ testView.ColorMode = Tizen.NUI.ColorMode.UseOwnColor;
+ Assert.AreEqual(Tizen.NUI.ColorMode.UseOwnColor, testView.ColorMode, "colormode should be UseOwnColor");
+
+ testView.ColorMode = Tizen.NUI.ColorMode.UseParentColor;
+ Assert.AreEqual(Tizen.NUI.ColorMode.UseParentColor, testView.ColorMode, "colormode should be UseParentColor");
+
+ testView.ColorMode = Tizen.NUI.ColorMode.UseOwnMultiplyParentColor;
+ Assert.AreEqual(Tizen.NUI.ColorMode.UseOwnMultiplyParentColor, testView.ColorMode, "colormode should be UseOwnMultiplyParentColor");
+
+ testView.ColorMode = Tizen.NUI.ColorMode.UseOwnMultiplyParentAlpha;
+ Assert.AreEqual(Tizen.NUI.ColorMode.UseOwnMultiplyParentAlpha, testView.ColorMode, "colormode should be UseOwnMultiplyParentAlpha");
+
+ testView.Unparent();
+ testView.Dispose();
+ }
+
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns="http://tizen.org/ns/packages" api-version="9" package="Tizen.NUI.Devel.Tests" version="1.0.0">
+ <profile name="common" />
+ <ui-application appid="Tizen.NUI.Devel.Tests"
+ exec="Tizen.NUI.Devel.Tests.dll"
+ type="dotnet"
+ multiple="false"
+ taskmanage="true"
+ launch_mode="single">
+ <icon>Tizen.NUI.Devel.Tests.png</icon>
+ <label>Tizen.NUI.Devel.Tests</label>
+ </ui-application>
+ <privileges>
+ <privilege>http://tizen.org/privilege/appmanager.launch</privilege>
+ </privileges>
+</manifest>
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// The different targets a test action attribute can be applied to
+ /// </summary>
+ [Flags]
+ public enum ActionTargets
+ {
+ /// <summary>
+ /// Default target, which is determined by where the action attribute is attached
+ /// </summary>
+ Default = 0,
+
+ /// <summary>
+ /// Target a individual test case
+ /// </summary>
+ Test = 1,
+
+ /// <summary>
+ /// Target a suite of test cases
+ /// </summary>
+ Suite = 2
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012-2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Common;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.Internal.Builders;
+
+namespace NUnit.Framework.Api
+{
+ /// <summary>
+ /// DefaultTestAssemblyBuilder loads a single assembly and builds a TestSuite
+ /// containing test fixtures present in the assembly.
+ /// </summary>
+ public class DefaultTestAssemblyBuilder : ITestAssemblyBuilder
+ {
+ static Logger log = InternalTrace.GetLogger(typeof(DefaultTestAssemblyBuilder));
+
+ #region Instance Fields
+
+ /// <summary>
+ /// The default suite builder used by the test assembly builder.
+ /// </summary>
+ ISuiteBuilder _defaultSuiteBuilder;
+
+ #endregion
+
+ #region Constructor
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DefaultTestAssemblyBuilder"/> class.
+ /// </summary>
+ public DefaultTestAssemblyBuilder()
+ {
+ _defaultSuiteBuilder = new DefaultSuiteBuilder();
+ }
+
+ #endregion
+
+ #region Build Methods
+
+ /// <summary>
+ /// Build a suite of tests from a provided assembly
+ /// </summary>
+ /// <param name="assembly">The assembly from which tests are to be built</param>
+ /// <param name="options">A dictionary of options to use in building the suite</param>
+ /// <returns>
+ /// A TestSuite containing the tests found in the assembly
+ /// </returns>
+ public ITest Build(Assembly assembly, IDictionary<string, object> options)
+ {
+#if PORTABLE
+ log.Debug("Loading {0}", assembly.FullName);
+#else
+ log.Debug("Loading {0} in AppDomain {1}", assembly.FullName, AppDomain.CurrentDomain.FriendlyName);
+#endif
+
+#if SILVERLIGHT
+ string assemblyPath = AssemblyHelper.GetAssemblyName(assembly).Name;
+#elif PORTABLE
+ string assemblyPath = AssemblyHelper.GetAssemblyName(assembly).FullName;
+#else
+ string assemblyPath = AssemblyHelper.GetAssemblyPath(assembly);
+#endif
+
+ return Build(assembly, assemblyPath, options);
+ }
+
+ /// <summary>
+ /// Build a suite of tests given the filename of an assembly
+ /// </summary>
+ /// <param name="assemblyName">The filename of the assembly from which tests are to be built</param>
+ /// <param name="options">A dictionary of options to use in building the suite</param>
+ /// <returns>
+ /// A TestSuite containing the tests found in the assembly
+ /// </returns>
+ public ITest Build(string assemblyName, IDictionary<string, object> options)
+ {
+#if PORTABLE
+ log.Debug("Loading {0}", assemblyName);
+#else
+ log.Debug("Loading {0} in AppDomain {1}", assemblyName, AppDomain.CurrentDomain.FriendlyName);
+#endif
+
+ TestSuite testAssembly = null;
+
+ try
+ {
+ var assembly = AssemblyHelper.Load(assemblyName);
+
+ if (assembly == null)
+ throw new Exception("assembly is null");
+
+ testAssembly = Build(assembly, assemblyName, options);
+ }
+ catch (Exception ex)
+ {
+ testAssembly = new TestAssembly(assemblyName);
+ testAssembly.RunState = RunState.NotRunnable;
+ testAssembly.Properties.Set(PropertyNames.SkipReason, ex.Message);
+ }
+
+ return testAssembly;
+ }
+
+ private TestSuite Build(Assembly assembly, string assemblyPath, IDictionary<string, object> options)
+ {
+ TestSuite testAssembly = null;
+
+ try
+ {
+ if (options.ContainsKey(PackageSettings.DefaultTestNamePattern))
+ TestNameGenerator.DefaultTestNamePattern = options[PackageSettings.DefaultTestNamePattern] as string;
+
+ if (options.ContainsKey(PackageSettings.TestParameters))
+ {
+ string parameters = options[PackageSettings.TestParameters] as string;
+ if (!string.IsNullOrEmpty(parameters))
+ foreach (string param in parameters.Split(new[] { ';' }))
+ {
+ int eq = param.IndexOf("=");
+
+ if (eq > 0 && eq < param.Length - 1)
+ {
+ var name = param.Substring(0, eq);
+ var val = param.Substring(eq + 1);
+
+ TestContext.Parameters.Add(name, val);
+ }
+ }
+ }
+
+ IList fixtureNames = null;
+ if (options.ContainsKey(PackageSettings.LOAD))
+ fixtureNames = options[PackageSettings.LOAD] as IList;
+ var fixtures = GetFixtures(assembly, fixtureNames);
+
+ testAssembly = BuildTestAssembly(assembly, assemblyPath, fixtures);
+ }
+ catch (Exception ex)
+ {
+ testAssembly = new TestAssembly(assemblyPath);
+ testAssembly.RunState = RunState.NotRunnable;
+ testAssembly.Properties.Set(PropertyNames.SkipReason, ex.Message);
+ }
+
+ return testAssembly;
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ private IList<Test> GetFixtures(Assembly assembly, IList names)
+ {
+ var fixtures = new List<Test>();
+ log.Debug("Examining assembly for test fixtures");
+
+ var testTypes = GetCandidateFixtureTypes(assembly, names);
+
+ log.Debug("Found {0} classes to examine", testTypes.Count);
+#if LOAD_TIMING
+ System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
+ timer.Start();
+#endif
+ int testcases = 0;
+ foreach (Type testType in testTypes)
+ {
+ var typeInfo = new TypeWrapper(testType);
+
+ try
+ {
+ if (_defaultSuiteBuilder.CanBuildFrom(typeInfo))
+ {
+ Test fixture = _defaultSuiteBuilder.BuildFrom(typeInfo);
+ fixtures.Add(fixture);
+ testcases += fixture.TestCaseCount;
+ }
+ }
+ catch (Exception ex)
+ {
+ log.Error(ex.ToString());
+ }
+ }
+
+#if LOAD_TIMING
+ log.Debug("Found {0} fixtures with {1} test cases in {2} seconds", fixtures.Count, testcases, timer.Elapsed);
+#else
+ log.Debug("Found {0} fixtures with {1} test cases", fixtures.Count, testcases);
+#endif
+
+ return fixtures;
+ }
+
+ private IList<Type> GetCandidateFixtureTypes(Assembly assembly, IList names)
+ {
+ var types = assembly.GetTypes();
+
+ if (names == null || names.Count == 0)
+ return types;
+
+ var result = new List<Type>();
+
+ foreach (string name in names)
+ {
+ Type fixtureType = assembly.GetType(name);
+ if (fixtureType != null)
+ result.Add(fixtureType);
+ else
+ {
+ string prefix = name + ".";
+
+ foreach (Type type in types)
+ if (type.FullName.StartsWith(prefix))
+ result.Add(type);
+ }
+ }
+
+ return result;
+ }
+
+ private TestSuite BuildTestAssembly(Assembly assembly, string assemblyName, IList<Test> fixtures)
+ {
+ TestSuite testAssembly = new TestAssembly(assembly, assemblyName);
+
+ if (fixtures.Count == 0)
+ {
+ testAssembly.RunState = RunState.NotRunnable;
+ testAssembly.Properties.Set(PropertyNames.SkipReason, "Has no TestFixtures");
+ }
+ else
+ {
+ NamespaceTreeBuilder treeBuilder =
+ new NamespaceTreeBuilder(testAssembly);
+ treeBuilder.Add(fixtures);
+ testAssembly = treeBuilder.RootSuite;
+ }
+
+ testAssembly.ApplyAttributesToTest(assembly);
+
+#if !PORTABLE
+#if !SILVERLIGHT
+ testAssembly.Properties.Set(PropertyNames.ProcessID, System.Diagnostics.Process.GetCurrentProcess().Id);
+#endif
+ testAssembly.Properties.Set(PropertyNames.AppDomain, AppDomain.CurrentDomain.FriendlyName);
+#endif
+
+ // TODO: Make this an option? Add Option to sort assemblies as well?
+ // [tronghieu.d] - no need to sort tcs, to sync with tc order of tct-mgr
+ //testAssembly.Sort();
+
+ return testAssembly;
+ }
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009-2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Linq;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Reflection;
+using System.Web.UI;
+using NUnit.Common;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework.Api
+{
+ /// <summary>
+ /// FrameworkController provides a facade for use in loading, browsing
+ /// and running tests without requiring a reference to the NUnit
+ /// framework. All calls are encapsulated in constructors for
+ /// this class and its nested classes, which only require the
+ /// types of the Common Type System as arguments.
+ ///
+ /// The controller supports four actions: Load, Explore, Count and Run.
+ /// They are intended to be called by a driver, which should allow for
+ /// proper sequencing of calls. Load must be called before any of the
+ /// other actions. The driver may support other actions, such as
+ /// reload on run, by combining these calls.
+ /// </summary>
+ //[Serializable]
+ public class FrameworkController : LongLivedMarshalByRefObject
+ {
+#if !PORTABLE && !SILVERLIGHT
+ private const string LOG_FILE_FORMAT = "InternalTrace.{0}.{1}.log";
+#endif
+
+ // Pre-loaded test assembly, if passed in constructor
+ private readonly Assembly _testAssembly;
+
+ #region Constructors
+
+ /// <summary>
+ /// Construct a FrameworkController using the default builder and runner.
+ /// </summary>
+ /// <param name="assemblyNameOrPath">The AssemblyName or path to the test assembly</param>
+ /// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
+ /// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
+ public FrameworkController(string assemblyNameOrPath, string idPrefix, IDictionary settings)
+ {
+ this.Builder = new DefaultTestAssemblyBuilder();
+ this.Runner = new NUnitTestAssemblyRunner(this.Builder);
+
+ Test.IdPrefix = idPrefix;
+ Initialize(assemblyNameOrPath, settings);
+ }
+
+ /// <summary>
+ /// Construct a FrameworkController using the default builder and runner.
+ /// </summary>
+ /// <param name="assembly">The test assembly</param>
+ /// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
+ /// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
+ public FrameworkController(Assembly assembly, string idPrefix, IDictionary settings)
+ : this(assembly.FullName, idPrefix, settings)
+ {
+ _testAssembly = assembly;
+ }
+
+ /// <summary>
+ /// Construct a FrameworkController, specifying the types to be used
+ /// for the runner and builder. This constructor is provided for
+ /// purposes of development.
+ /// </summary>
+ /// <param name="assemblyNameOrPath">The full AssemblyName or the path to the test assembly</param>
+ /// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
+ /// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
+ /// <param name="runnerType">The Type of the test runner</param>
+ /// <param name="builderType">The Type of the test builder</param>
+ public FrameworkController(string assemblyNameOrPath, string idPrefix, IDictionary settings, string runnerType, string builderType)
+ {
+ Builder = (ITestAssemblyBuilder)Reflect.Construct(Type.GetType(builderType));
+ Runner = (ITestAssemblyRunner)Reflect.Construct(Type.GetType(runnerType), new object[] { Builder });
+
+ Test.IdPrefix = idPrefix ?? "";
+ Initialize(assemblyNameOrPath, settings);
+ }
+
+ /// <summary>
+ /// Construct a FrameworkController, specifying the types to be used
+ /// for the runner and builder. This constructor is provided for
+ /// purposes of development.
+ /// </summary>
+ /// <param name="assembly">The test assembly</param>
+ /// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
+ /// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
+ /// <param name="runnerType">The Type of the test runner</param>
+ /// <param name="builderType">The Type of the test builder</param>
+ public FrameworkController(Assembly assembly, string idPrefix, IDictionary settings, string runnerType, string builderType)
+ : this(assembly.FullName, idPrefix, settings, runnerType, builderType)
+ {
+ _testAssembly = assembly;
+ }
+
+ private void Initialize(string assemblyPath, IDictionary settings)
+ {
+ AssemblyNameOrPath = assemblyPath;
+
+ var newSettings = settings as IDictionary<string, object>;
+ Settings = newSettings ?? settings.Cast<DictionaryEntry>().ToDictionary(de => (string)de.Key, de => de.Value);
+
+ if (Settings.ContainsKey(PackageSettings.InternalTraceLevel))
+ {
+ var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)Settings[PackageSettings.InternalTraceLevel], true);
+
+ if (Settings.ContainsKey(PackageSettings.InternalTraceWriter))
+ InternalTrace.Initialize((TextWriter)Settings[PackageSettings.InternalTraceWriter], traceLevel);
+#if !PORTABLE && !SILVERLIGHT
+ else
+ {
+ var workDirectory = Settings.ContainsKey(PackageSettings.WorkDirectory) ? (string)Settings[PackageSettings.WorkDirectory] : Env.DefaultWorkDirectory;
+ var logName = string.Format(LOG_FILE_FORMAT, Process.GetCurrentProcess().Id, Path.GetFileName(assemblyPath));
+ InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
+ }
+#endif
+ }
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Gets the ITestAssemblyBuilder used by this controller instance.
+ /// </summary>
+ /// <value>The builder.</value>
+ public ITestAssemblyBuilder Builder { get; private set; }
+
+ /// <summary>
+ /// Gets the ITestAssemblyRunner used by this controller instance.
+ /// </summary>
+ /// <value>The runner.</value>
+ public ITestAssemblyRunner Runner { get; private set; }
+
+ /// <summary>
+ /// Gets the AssemblyName or the path for which this FrameworkController was created
+ /// </summary>
+ public string AssemblyNameOrPath { get; private set; }
+
+ /// <summary>
+ /// Gets the Assembly for which this
+ /// </summary>
+ public Assembly Assembly { get; private set; }
+
+ /// <summary>
+ /// Gets a dictionary of settings for the FrameworkController
+ /// </summary>
+ internal IDictionary<string, object> Settings { get; private set; }
+
+ #endregion
+
+ #region Public Action methods Used by nunit.driver for running portable tests
+
+ /// <summary>
+ /// Loads the tests in the assembly
+ /// </summary>
+ /// <returns></returns>
+ public string LoadTests()
+ {
+ if (_testAssembly != null)
+ Runner.Load(_testAssembly, Settings);
+ else
+ Runner.Load(AssemblyNameOrPath, Settings);
+
+ return Runner.LoadedTest.ToXml(false).OuterXml;
+ }
+
+ /// <summary>
+ /// Returns info about the tests in an assembly
+ /// </summary>
+ /// <param name="filter">A string containing the XML representation of the filter to use</param>
+ /// <returns>The XML result of exploring the tests</returns>
+ public string ExploreTests(string filter)
+ {
+ Guard.ArgumentNotNull(filter, "filter");
+
+ if (Runner.LoadedTest == null)
+ throw new InvalidOperationException("The Explore method was called but no test has been loaded");
+
+ // TODO: Make use of the filter
+ return Runner.LoadedTest.ToXml(true).OuterXml;
+ }
+
+ /// <summary>
+ /// Runs the tests in an assembly
+ /// </summary>
+ /// <param name="filter">A string containing the XML representation of the filter to use</param>
+ /// <returns>The XML result of the test run</returns>
+ public string RunTests(string filter)
+ {
+ Guard.ArgumentNotNull(filter, "filter");
+
+ TNode result = Runner.Run(new TestProgressReporter(null), TestFilter.FromXml(filter)).ToXml(true);
+
+ // Insert elements as first child in reverse order
+ if (Settings != null) // Some platforms don't have settings
+ InsertSettingsElement(result, Settings);
+#if !PORTABLE && !SILVERLIGHT
+ InsertEnvironmentElement(result);
+#endif
+
+ // Ensure that the CallContext of the thread is not polluted
+ // by our TestExecutionContext, which is not serializable.
+ TestExecutionContext.ClearCurrentContext();
+
+ return result.OuterXml;
+ }
+
+#if !NET_2_0
+
+ class ActionCallback : ICallbackEventHandler
+ {
+ readonly Action<string> _callback;
+
+ public ActionCallback(Action<string> callback)
+ {
+ _callback = callback;
+ }
+
+ public string GetCallbackResult()
+ {
+ throw new NotImplementedException();
+ }
+
+ public void RaiseCallbackEvent(string report)
+ {
+ if(_callback != null)
+ _callback.Invoke(report);
+ }
+ }
+
+ /// <summary>
+ /// Runs the tests in an assembly syncronously reporting back the test results through the callback
+ /// or through the return value
+ /// </summary>
+ /// <param name="callback">The callback that receives the test results</param>
+ /// <param name="filter">A string containing the XML representation of the filter to use</param>
+ /// <returns>The XML result of the test run</returns>
+ public string RunTests(Action<string> callback, string filter)
+ {
+ Guard.ArgumentNotNull(filter, "filter");
+
+ var handler = new ActionCallback(callback);
+
+ TNode result = Runner.Run(new TestProgressReporter(handler), TestFilter.FromXml(filter)).ToXml(true);
+
+ // Insert elements as first child in reverse order
+ if (Settings != null) // Some platforms don't have settings
+ InsertSettingsElement(result, Settings);
+#if !PORTABLE && !SILVERLIGHT
+ InsertEnvironmentElement(result);
+#endif
+
+ // Ensure that the CallContext of the thread is not polluted
+ // by our TestExecutionContext, which is not serializable.
+ TestExecutionContext.ClearCurrentContext();
+
+ return result.OuterXml;
+ }
+
+ /// <summary>
+ /// Runs the tests in an assembly asyncronously reporting back the test results through the callback
+ /// </summary>
+ /// <param name="callback">The callback that receives the test results</param>
+ /// <param name="filter">A string containing the XML representation of the filter to use</param>
+ private void RunAsync(Action<string> callback, string filter)
+ {
+ Guard.ArgumentNotNull(filter, "filter");
+
+ var handler = new ActionCallback(callback);
+
+ Runner.RunAsync(new TestProgressReporter(handler), TestFilter.FromXml(filter));
+ }
+#endif
+
+ /// <summary>
+ /// Stops the test run
+ /// </summary>
+ /// <param name="force">True to force the stop, false for a cooperative stop</param>
+ public void StopRun(bool force)
+ {
+ Runner.StopRun(force);
+ }
+
+ /// <summary>
+ /// Counts the number of test cases in the loaded TestSuite
+ /// </summary>
+ /// <param name="filter">A string containing the XML representation of the filter to use</param>
+ /// <returns>The number of tests</returns>
+ public int CountTests(string filter)
+ {
+ Guard.ArgumentNotNull(filter, "filter");
+
+ return Runner.CountTestCases(TestFilter.FromXml(filter));
+ }
+
+ #endregion
+
+ #region Private Action Methods Used by Nested Classes
+
+ private void LoadTests(ICallbackEventHandler handler)
+ {
+ handler.RaiseCallbackEvent(LoadTests());
+ }
+
+ private void ExploreTests(ICallbackEventHandler handler, string filter)
+ {
+ Guard.ArgumentNotNull(filter, "filter");
+
+ if (Runner.LoadedTest == null)
+ throw new InvalidOperationException("The Explore method was called but no test has been loaded");
+
+ // TODO: Make use of the filter
+ handler.RaiseCallbackEvent(Runner.LoadedTest.ToXml(true).OuterXml);
+ }
+
+ private void RunTests(ICallbackEventHandler handler, string filter)
+ {
+ Guard.ArgumentNotNull(filter, "filter");
+
+ TNode result = Runner.Run(new TestProgressReporter(handler), TestFilter.FromXml(filter)).ToXml(true);
+
+ // Insert elements as first child in reverse order
+ if (Settings != null) // Some platforms don't have settings
+ InsertSettingsElement(result, Settings);
+#if !PORTABLE && !SILVERLIGHT
+ InsertEnvironmentElement(result);
+#endif
+
+ // Ensure that the CallContext of the thread is not polluted
+ // by our TestExecutionContext, which is not serializable.
+ TestExecutionContext.ClearCurrentContext();
+
+ handler.RaiseCallbackEvent(result.OuterXml);
+ }
+
+ private void RunAsync(ICallbackEventHandler handler, string filter)
+ {
+ Guard.ArgumentNotNull(filter, "filter");
+
+ Runner.RunAsync(new TestProgressReporter(handler), TestFilter.FromXml(filter));
+ }
+
+ private void StopRun(ICallbackEventHandler handler, bool force)
+ {
+ StopRun(force);
+ }
+
+ private void CountTests(ICallbackEventHandler handler, string filter)
+ {
+ handler.RaiseCallbackEvent(CountTests(filter).ToString());
+ }
+
+#if !PORTABLE && !SILVERLIGHT
+ /// <summary>
+ /// Inserts environment element
+ /// </summary>
+ /// <param name="targetNode">Target node</param>
+ /// <returns>The new node</returns>
+ public static TNode InsertEnvironmentElement(TNode targetNode)
+ {
+ TNode env = new TNode("environment");
+ targetNode.ChildNodes.Insert(0, env);
+
+ env.AddAttribute("framework-version", Assembly.GetExecutingAssembly().GetName().Version.ToString());
+ env.AddAttribute("clr-version", Environment.Version.ToString());
+ env.AddAttribute("os-version", Environment.OSVersion.ToString());
+ env.AddAttribute("platform", Environment.OSVersion.Platform.ToString());
+#if !NETCF
+ env.AddAttribute("cwd", Environment.CurrentDirectory);
+ env.AddAttribute("machine-name", Environment.MachineName);
+ env.AddAttribute("user", Environment.UserName);
+ env.AddAttribute("user-domain", Environment.UserDomainName);
+#endif
+ env.AddAttribute("culture", CultureInfo.CurrentCulture.ToString());
+ env.AddAttribute("uiculture", CultureInfo.CurrentUICulture.ToString());
+ env.AddAttribute("os-architecture", GetProcessorArchitecture());
+
+ return env;
+ }
+
+ private static string GetProcessorArchitecture()
+ {
+ return IntPtr.Size == 8 ? "x64" : "x86";
+ }
+#endif
+
+ /// <summary>
+ /// Inserts settings element
+ /// </summary>
+ /// <param name="targetNode">Target node</param>
+ /// <param name="settings">Settings dictionary</param>
+ /// <returns>The new node</returns>
+ public static TNode InsertSettingsElement(TNode targetNode, IDictionary<string, object> settings)
+ {
+ TNode settingsNode = new TNode("settings");
+ targetNode.ChildNodes.Insert(0, settingsNode);
+
+ foreach (string key in settings.Keys)
+ AddSetting(settingsNode, key, settings[key]);
+
+#if PARALLEL
+ // Add default values for display
+ if (!settings.ContainsKey(PackageSettings.NumberOfTestWorkers))
+ AddSetting(settingsNode, PackageSettings.NumberOfTestWorkers, NUnitTestAssemblyRunner.DefaultLevelOfParallelism);
+#endif
+
+ return settingsNode;
+ }
+
+ private static void AddSetting(TNode settingsNode, string name, object value)
+ {
+ TNode setting = new TNode("setting");
+ setting.AddAttribute("name", name);
+ setting.AddAttribute("value", value.ToString());
+
+ settingsNode.ChildNodes.Add(setting);
+ }
+
+ #endregion
+
+ #region Nested Action Classes
+
+ #region TestContollerAction
+
+ /// <summary>
+ /// FrameworkControllerAction is the base class for all actions
+ /// performed against a FrameworkController.
+ /// </summary>
+ public abstract class FrameworkControllerAction : LongLivedMarshalByRefObject
+ {
+ }
+
+ #endregion
+
+ #region LoadTestsAction
+
+ /// <summary>
+ /// LoadTestsAction loads a test into the FrameworkController
+ /// </summary>
+ public class LoadTestsAction : FrameworkControllerAction
+ {
+ /// <summary>
+ /// LoadTestsAction loads the tests in an assembly.
+ /// </summary>
+ /// <param name="controller">The controller.</param>
+ /// <param name="handler">The callback handler.</param>
+ public LoadTestsAction(FrameworkController controller, object handler)
+ {
+ controller.LoadTests((ICallbackEventHandler)handler);
+ }
+ }
+
+ #endregion
+
+ #region ExploreTestsAction
+
+ /// <summary>
+ /// ExploreTestsAction returns info about the tests in an assembly
+ /// </summary>
+ public class ExploreTestsAction : FrameworkControllerAction
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExploreTestsAction"/> class.
+ /// </summary>
+ /// <param name="controller">The controller for which this action is being performed.</param>
+ /// <param name="filter">Filter used to control which tests are included (NYI)</param>
+ /// <param name="handler">The callback handler.</param>
+ public ExploreTestsAction(FrameworkController controller, string filter, object handler)
+ {
+ controller.ExploreTests((ICallbackEventHandler)handler, filter);
+ }
+ }
+
+ #endregion
+
+ #region CountTestsAction
+
+ /// <summary>
+ /// CountTestsAction counts the number of test cases in the loaded TestSuite
+ /// held by the FrameworkController.
+ /// </summary>
+ public class CountTestsAction : FrameworkControllerAction
+ {
+ /// <summary>
+ /// Construct a CountsTestAction and perform the count of test cases.
+ /// </summary>
+ /// <param name="controller">A FrameworkController holding the TestSuite whose cases are to be counted</param>
+ /// <param name="filter">A string containing the XML representation of the filter to use</param>
+ /// <param name="handler">A callback handler used to report results</param>
+ public CountTestsAction(FrameworkController controller, string filter, object handler)
+ {
+ controller.CountTests((ICallbackEventHandler)handler, filter);
+ }
+ }
+
+ #endregion
+
+ #region RunTestsAction
+
+ /// <summary>
+ /// RunTestsAction runs the loaded TestSuite held by the FrameworkController.
+ /// </summary>
+ public class RunTestsAction : FrameworkControllerAction
+ {
+ /// <summary>
+ /// Construct a RunTestsAction and run all tests in the loaded TestSuite.
+ /// </summary>
+ /// <param name="controller">A FrameworkController holding the TestSuite to run</param>
+ /// <param name="filter">A string containing the XML representation of the filter to use</param>
+ /// <param name="handler">A callback handler used to report results</param>
+ public RunTestsAction(FrameworkController controller, string filter, object handler)
+ {
+ controller.RunTests((ICallbackEventHandler)handler, filter);
+ }
+ }
+
+ #endregion
+
+ #region RunAsyncAction
+
+ /// <summary>
+ /// RunAsyncAction initiates an asynchronous test run, returning immediately
+ /// </summary>
+ public class RunAsyncAction : FrameworkControllerAction
+ {
+ /// <summary>
+ /// Construct a RunAsyncAction and run all tests in the loaded TestSuite.
+ /// </summary>
+ /// <param name="controller">A FrameworkController holding the TestSuite to run</param>
+ /// <param name="filter">A string containing the XML representation of the filter to use</param>
+ /// <param name="handler">A callback handler used to report results</param>
+ public RunAsyncAction(FrameworkController controller, string filter, object handler)
+ {
+ controller.RunAsync((ICallbackEventHandler)handler, filter);
+ }
+ }
+
+ #endregion
+
+ #region StopRunAction
+
+ /// <summary>
+ /// StopRunAction stops an ongoing run.
+ /// </summary>
+ public class StopRunAction : FrameworkControllerAction
+ {
+ /// <summary>
+ /// Construct a StopRunAction and stop any ongoing run. If no
+ /// run is in process, no error is raised.
+ /// </summary>
+ /// <param name="controller">The FrameworkController for which a run is to be stopped.</param>
+ /// <param name="force">True the stop should be forced, false for a cooperative stop.</param>
+ /// <param name="handler">>A callback handler used to report results</param>
+ /// <remarks>A forced stop will cause threads and processes to be killed as needed.</remarks>
+ public StopRunAction(FrameworkController controller, bool force, object handler)
+ {
+ controller.StopRun((ICallbackEventHandler)handler, force);
+ }
+ }
+
+ #endregion
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Api
+{
+ /// <summary>
+ /// The ITestAssemblyBuilder interface is implemented by a class
+ /// that is able to build a suite of tests given an assembly or
+ /// an assembly filename.
+ /// </summary>
+ public interface ITestAssemblyBuilder
+ {
+ /// <summary>
+ /// Build a suite of tests from a provided assembly
+ /// </summary>
+ /// <param name="assembly">The assembly from which tests are to be built</param>
+ /// <param name="options">A dictionary of options to use in building the suite</param>
+ /// <returns>A TestSuite containing the tests found in the assembly</returns>
+ ITest Build(Assembly assembly, IDictionary<string, object> options);
+
+ /// <summary>
+ /// Build a suite of tests given the filename of an assembly
+ /// </summary>
+ /// <param name="assemblyName">The filename of the assembly from which tests are to be built</param>
+ /// <param name="options">A dictionary of options to use in building the suite</param>
+ /// <returns>A TestSuite containing the tests found in the assembly</returns>
+ ITest Build(string assemblyName, IDictionary<string, object> options);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Api
+{
+ /// <summary>
+ /// The ITestAssemblyRunner interface is implemented by classes
+ /// that are able to execute a suite of tests loaded
+ /// from an assembly.
+ /// </summary>
+ public interface ITestAssemblyRunner
+ {
+ #region Properties
+
+ /// <summary>
+ /// Gets the tree of loaded tests, or null if
+ /// no tests have been loaded.
+ /// </summary>
+ ITest LoadedTest { get; }
+
+ /// <summary>
+ /// Gets the tree of test results, if the test
+ /// run is completed, otherwise null.
+ /// </summary>
+ ITestResult Result { get; }
+
+ /// <summary>
+ /// Indicates whether a test has been loaded
+ /// </summary>
+ bool IsTestLoaded { get; }
+
+ /// <summary>
+ /// Indicates whether a test is currently running
+ /// </summary>
+ bool IsTestRunning { get; }
+
+ /// <summary>
+ /// Indicates whether a test run is complete
+ /// </summary>
+ bool IsTestComplete { get; }
+
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Loads the tests found in an Assembly, returning an
+ /// indication of whether or not the load succeeded.
+ /// </summary>
+ /// <param name="assemblyName">File name of the assembly to load</param>
+ /// <param name="settings">Dictionary of options to use in loading the test</param>
+ /// <returns>An ITest representing the loaded tests</returns>
+ ITest Load(string assemblyName, IDictionary<string, object> settings);
+
+ /// <summary>
+ /// Loads the tests found in an Assembly, returning an
+ /// indication of whether or not the load succeeded.
+ /// </summary>
+ /// <param name="assembly">The assembly to load</param>
+ /// <param name="settings">Dictionary of options to use in loading the test</param>
+ /// <returns>An ITest representing the loaded tests</returns>
+ ITest Load(Assembly assembly, IDictionary<string, object> settings);
+
+ /// <summary>
+ /// Count Test Cases using a filter
+ /// </summary>
+ /// <param name="filter">The filter to apply</param>
+ /// <returns>The number of test cases found</returns>
+ int CountTestCases(ITestFilter filter);
+
+ /// <summary>
+ /// Run selected tests and return a test result. The test is run synchronously,
+ /// and the listener interface is notified as it progresses.
+ /// </summary>
+ /// <param name="listener">Interface to receive ITestListener notifications.</param>
+ /// <param name="filter">A test filter used to select tests to be run</param>
+ ITestResult Run(ITestListener listener, ITestFilter filter);
+
+ /// <summary>
+ /// Run selected tests asynchronously, notifying the listener interface as it progresses.
+ /// </summary>
+ /// <param name="listener">Interface to receive EventListener notifications.</param>
+ /// <param name="filter">A test filter used to select tests to be run</param>
+ void RunAsync(ITestListener listener, ITestFilter filter);
+
+ /// <summary>
+ /// Wait for the ongoing run to complete.
+ /// </summary>
+ /// <param name="timeout">Time to wait in milliseconds</param>
+ /// <returns>True if the run completed, otherwise false</returns>
+ bool WaitForCompletion(int timeout);
+
+ /// <summary>
+ /// Signal any test run that is in process to stop. Return without error if no test is running.
+ /// </summary>
+ /// <param name="force">If true, kill any test-running threads</param>
+ void StopRun(bool force);
+
+ #endregion
+
+ #if TIZEN
+ Dictionary<string, ITest> GetTestcaseIDList();
+ #endif
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012-2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.IO;
+using System.Reflection;
+using System.Threading;
+using NUnit.Common;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.TUnit;
+using NUnit.Framework.Internal.Execution;
+using System.Collections.Generic;
+
+#if !SILVERLIGHT && !NETCF && !PORTABLE
+using System.Diagnostics;
+//using System.Windows.Forms;
+#endif
+
+namespace NUnit.Framework.Api
+{
+ /// <summary>
+ /// Implementation of ITestAssemblyRunner
+ /// </summary>
+ public class NUnitTestAssemblyRunner : ITestAssemblyRunner
+ {
+ private static Logger log = InternalTrace.GetLogger("DefaultTestAssemblyRunner");
+
+ private ITestAssemblyBuilder _builder;
+ private ManualResetEvent _runComplete = new ManualResetEvent(false);
+
+ private ITestListener _listener;
+#if TIZEN
+ private Dictionary<string, ITest> TestcaseIDDic;
+#endif
+
+#if !SILVERLIGHT && !NETCF && !PORTABLE
+ // Saved Console.Out and Console.Error
+ private TextWriter _savedOut;
+ private TextWriter _savedErr;
+#endif
+
+#if PARALLEL
+ // Event Pump
+ private EventPump _pump;
+#endif
+
+ #region Constructors
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NUnitTestAssemblyRunner"/> class.
+ /// </summary>
+ /// <param name="builder">The builder.</param>
+ public NUnitTestAssemblyRunner(ITestAssemblyBuilder builder)
+ {
+ _builder = builder;
+#if TIZEN
+ TestcaseIDDic = new Dictionary<string, ITest>();
+#endif
+ }
+
+ #endregion
+
+ #region Properties
+
+#if PARALLEL
+ /// <summary>
+ /// Gets the default level of parallel execution (worker threads)
+ /// </summary>
+ public static int DefaultLevelOfParallelism
+ {
+#if NETCF
+ get { return 2; }
+#else
+ get { return Math.Max(Environment.ProcessorCount, 2); }
+#endif
+ }
+#endif
+
+ /// <summary>
+ /// The tree of tests that was loaded by the builder
+ /// </summary>
+ public ITest LoadedTest { get; private set; }
+
+ /// <summary>
+ /// The test result, if a run has completed
+ /// </summary>
+ public ITestResult Result
+ {
+ get { return TopLevelWorkItem == null ? null : TopLevelWorkItem.Result; }
+ }
+
+ /// <summary>
+ /// Indicates whether a test is loaded
+ /// </summary>
+ public bool IsTestLoaded
+ {
+ get { return LoadedTest != null; }
+ }
+
+ /// <summary>
+ /// Indicates whether a test is running
+ /// </summary>
+ public bool IsTestRunning
+ {
+ get { return TopLevelWorkItem != null && TopLevelWorkItem.State == WorkItemState.Running; }
+ }
+
+ /// <summary>
+ /// Indicates whether a test run is complete
+ /// </summary>
+ public bool IsTestComplete
+ {
+ get { return TopLevelWorkItem != null && TopLevelWorkItem.State == WorkItemState.Complete; }
+ }
+
+ /// <summary>
+ /// Our settings, specified when loading the assembly
+ /// </summary>
+ private IDictionary<string, object> Settings { get; set; }
+
+ /// <summary>
+ /// The top level WorkItem created for the assembly as a whole
+ /// </summary>
+ private WorkItem TopLevelWorkItem { get; set; }
+
+ /// <summary>
+ /// The TestExecutionContext for the top level WorkItem
+ /// </summary>
+ private TestExecutionContext Context { get; set; }
+
+ #endregion
+
+ #region Public Methods
+
+ /// <summary>
+ /// Loads the tests found in an Assembly
+ /// </summary>
+ /// <param name="assemblyName">File name of the assembly to load</param>
+ /// <param name="settings">Dictionary of option settings for loading the assembly</param>
+ /// <returns>True if the load was successful</returns>
+ public ITest Load(string assemblyName, IDictionary<string, object> settings)
+ {
+ Settings = settings;
+
+ if (settings.ContainsKey(PackageSettings.RandomSeed))
+ Randomizer.InitialSeed = (int)settings[PackageSettings.RandomSeed];
+
+ return LoadedTest = _builder.Build(assemblyName, settings);
+
+ }
+
+ /// <summary>
+ /// Loads the tests found in an Assembly
+ /// </summary>
+ /// <param name="assembly">The assembly to load</param>
+ /// <param name="settings">Dictionary of option settings for loading the assembly</param>
+ /// <returns>True if the load was successful</returns>
+ public ITest Load(Assembly assembly, IDictionary<string, object> settings)
+ {
+ Settings = settings;
+
+ if (settings.ContainsKey(PackageSettings.RandomSeed))
+ Randomizer.InitialSeed = (int)settings[PackageSettings.RandomSeed];
+
+ LoadedTest = _builder.Build(assembly, settings);
+ MakeTestcaseIDDic(LoadedTest);
+ return LoadedTest;
+ }
+
+#if TIZEN
+ ///// <summary>
+ /// Make Testcase ID Dictionary
+ public void MakeTestcaseIDDic(ITest testsuite)
+ {
+ foreach (ITest testmethod in testsuite.Tests)
+ {
+ if (testmethod.IsSuite)
+ {
+ MakeTestcaseIDDic(testmethod);
+ }
+ else
+ {
+ TestcaseIDDic.Add(testmethod.FullName, testmethod);
+ }
+ }
+ }
+
+ ///// <summary>
+ /// Get Testcase ID List
+ /// </summary>
+ /// <returns>Return Dictionary of TestcaseID</returns>
+ public Dictionary<string, ITest> GetTestcaseIDList()
+ {
+ return TestcaseIDDic;
+ }
+#endif
+
+ /// <summary>
+ /// Count Test Cases using a filter
+ /// </summary>
+ /// <param name="filter">The filter to apply</param>
+ /// <returns>The number of test cases found</returns>
+ public int CountTestCases(ITestFilter filter)
+ {
+ if (LoadedTest == null)
+ throw new InvalidOperationException("The CountTestCases method was called but no test has been loaded");
+
+ return CountTestCases(LoadedTest, filter);
+ }
+
+ /// <summary>
+ /// Run selected tests and return a test result. The test is run synchronously,
+ /// and the listener interface is notified as it progresses.
+ /// </summary>
+ /// <param name="listener">Interface to receive EventListener notifications.</param>
+ /// <param name="filter">A test filter used to select tests to be run</param>
+ /// <returns></returns>
+ public ITestResult Run(ITestListener listener, ITestFilter filter)
+ {
+ _listener = listener;
+ RunAsync(listener, filter);
+
+ return Result;
+ }
+
+ /// <summary>
+ /// Run selected tests asynchronously, notifying the listener interface as it progresses.
+ /// </summary>
+ /// <param name="listener">Interface to receive EventListener notifications.</param>
+ /// <param name="filter">A test filter used to select tests to be run</param>
+ /// <remarks>
+ /// RunAsync is a template method, calling various abstract and
+ /// virtual methods to be overridden by derived classes.
+ /// </remarks>
+ public void RunAsync(ITestListener listener, ITestFilter filter)
+ {
+ log.Info("Running tests");
+ if (LoadedTest == null)
+ throw new InvalidOperationException("The Run method was called but no test has been loaded");
+
+ _runComplete.Reset();
+
+ CreateTestExecutionContext(listener);
+
+ TopLevelWorkItem = WorkItem.CreateWorkItem(LoadedTest, filter);
+ TopLevelWorkItem.InitializeContext(Context);
+ TopLevelWorkItem.Completed += OnRunCompleted;
+
+#if TIZEN
+ TSettings tsetting = TSettings.GetInstance();
+ if (tsetting.IsSlaveMode && !tsetting.IsManual)
+ {
+ tsetting.NextStepRequest();
+
+ if (tsetting.Testcase_ID.Equals("0") || TSettings.IsLastTC == true)
+ {
+ return;
+ }
+ }
+#endif
+
+ StartRun(listener);
+ WaitForCompletion(Timeout.Infinite);
+ }
+
+ /// <summary>
+ /// Wait for the ongoing run to complete.
+ /// </summary>
+ /// <param name="timeout">Time to wait in milliseconds</param>
+ /// <returns>True if the run completed, otherwise false</returns>
+ public bool WaitForCompletion(int timeout)
+ {
+#if !SILVERLIGHT && !PORTABLE
+ return _runComplete.WaitOne(timeout, false);
+#else
+ return _runComplete.WaitOne(timeout);
+#endif
+ }
+
+ /// <summary>
+ /// Signal any test run that is in process to stop. Return without error if no test is running.
+ /// </summary>
+ /// <param name="force">If true, kill any tests that are currently running</param>
+ public void StopRun(bool force)
+ {
+ if (IsTestRunning)
+ {
+ Context.ExecutionStatus = force
+ ? TestExecutionStatus.AbortRequested
+ : TestExecutionStatus.StopRequested;
+
+ Context.Dispatcher.CancelRun(force);
+ }
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ /// <summary>
+ /// Initiate the test run.
+ /// </summary>
+ private void StartRun(ITestListener listener)
+ {
+#if !SILVERLIGHT && !NETCF && !PORTABLE
+ // Save Console.Out and Error for later restoration
+ _savedOut = Console.Out;
+ _savedErr = Console.Error;
+
+ Console.SetOut(new TextCapture(Console.Out));
+ Console.SetError(new EventListenerTextWriter("Error", Console.Error));
+#endif
+
+#if PARALLEL
+ // Queue and pump events, unless settings have SynchronousEvents == false
+ if (!Settings.ContainsKey(PackageSettings.SynchronousEvents) || !(bool)Settings[PackageSettings.SynchronousEvents])
+ {
+ QueuingEventListener queue = new QueuingEventListener();
+ Context.Listener = queue;
+
+ _pump = new EventPump(listener, queue.Events);
+ _pump.Start();
+ }
+#endif
+
+#if !NETCF
+ if (!System.Diagnostics.Debugger.IsAttached &&
+ Settings.ContainsKey(PackageSettings.DebugTests) &&
+ (bool)Settings[PackageSettings.DebugTests])
+ System.Diagnostics.Debugger.Launch();
+
+#if !SILVERLIGHT && !PORTABLE
+ if (Settings.ContainsKey(PackageSettings.PauseBeforeRun) &&
+ (bool)Settings[PackageSettings.PauseBeforeRun])
+ PauseBeforeRun();
+
+#endif
+#endif
+
+ Context.Dispatcher.Dispatch(TopLevelWorkItem);
+ }
+
+ /// <summary>
+ /// Create the initial TestExecutionContext used to run tests
+ /// </summary>
+ /// <param name="listener">The ITestListener specified in the RunAsync call</param>
+ private void CreateTestExecutionContext(ITestListener listener)
+ {
+ Context = new TestExecutionContext();
+
+ // Apply package settings to the context
+ if (Settings.ContainsKey(PackageSettings.DefaultTimeout))
+ Context.TestCaseTimeout = (int)Settings[PackageSettings.DefaultTimeout];
+ if (Settings.ContainsKey(PackageSettings.StopOnError))
+ Context.StopOnError = (bool)Settings[PackageSettings.StopOnError];
+
+ if (Settings.ContainsKey(PackageSettings.WorkDirectory))
+ Context.WorkDirectory = (string)Settings[PackageSettings.WorkDirectory];
+ else
+ Context.WorkDirectory = Env.DefaultWorkDirectory;
+
+ // Apply attributes to the context
+
+ // Set the listener - overriding runners may replace this
+ Context.Listener = listener;
+
+#if PARALLEL
+ int levelOfParallelism = GetLevelOfParallelism();
+
+ if (levelOfParallelism > 0)
+ Context.Dispatcher = new ParallelWorkItemDispatcher(levelOfParallelism);
+ else
+ Context.Dispatcher = new SimpleWorkItemDispatcher();
+#else
+ Context.Dispatcher = new SimpleWorkItemDispatcher();
+#endif
+ }
+
+ /// <summary>
+ /// Handle the the Completed event for the top level work item
+ /// </summary>
+ private void OnRunCompleted(object sender, EventArgs e)
+ {
+#if PARALLEL
+ if (_pump != null)
+ _pump.Dispose();
+#endif
+
+#if !SILVERLIGHT && !NETCF && !PORTABLE
+ Console.SetOut(_savedOut);
+ Console.SetError(_savedErr);
+#endif
+#if TIZEN
+ #region tronghieu.d - testkit-stub
+ TSettings tsetting = TSettings.GetInstance();
+ if (tsetting.IsSlaveMode && !tsetting.IsManual)
+ {
+ //tsetting.NextStepRequest();
+
+ if (tsetting.Testcase_ID != "0" && TSettings.IsLastTC != true)
+ {
+ StartRun(_listener);
+ return;
+ }
+ }
+ #endregion
+#endif
+
+ _runComplete.Set();
+ }
+
+ private int CountTestCases(ITest test, ITestFilter filter)
+ {
+ if (!test.IsSuite)
+ return 1;
+
+ int count = 0;
+ foreach (ITest child in test.Tests)
+ if (filter.Pass(child))
+ count += CountTestCases(child, filter);
+
+ return count;
+ }
+
+#if PARALLEL
+ private int GetLevelOfParallelism()
+ {
+ return Settings.ContainsKey(PackageSettings.NumberOfTestWorkers)
+ ? (int)Settings[PackageSettings.NumberOfTestWorkers]
+ : (LoadedTest.Properties.ContainsKey(PropertyNames.LevelOfParallelism)
+ ? (int)LoadedTest.Properties.Get(PropertyNames.LevelOfParallelism)
+ : NUnitTestAssemblyRunner.DefaultLevelOfParallelism);
+ }
+#endif
+
+#if !SILVERLIGHT && !NETCF && !PORTABLE
+ private static void PauseBeforeRun()
+ {
+ var process = Process.GetCurrentProcess();
+ string attachMessage = string.Format("Attach debugger to Process {0}.exe with Id {1} if desired.", process.ProcessName, process.Id);
+ //MessageBox.Show(attachMessage, process.ProcessName, MessageBoxButtons.OK, MessageBoxIcon.Information);
+ }
+#endif
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+
+using System;
+
+namespace NUnit.Framework
+{
+ public partial class Assert
+ {
+ #region Greater
+
+ #region Ints
+
+ /// <summary>
+ /// Verifies that the first int is greater than the second
+ /// int. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Greater(int arg1, int arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first int is greater than the second
+ /// int. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ public static void Greater(int arg1, int arg2)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Unsigned Ints
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ //[CLSCompliant(false)]
+ public static void Greater(uint arg1, uint arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ //[CLSCompliant(false)]
+ public static void Greater(uint arg1, uint arg2)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Longs
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Greater(long arg1, long arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ public static void Greater(long arg1, long arg2)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Unsigned Longs
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ //[CLSCompliant(false)]
+ public static void Greater(ulong arg1, ulong arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ //[CLSCompliant(false)]
+ public static void Greater(ulong arg1, ulong arg2)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Decimals
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Greater(decimal arg1, decimal arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ public static void Greater(decimal arg1, decimal arg2)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Doubles
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Greater(double arg1, double arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ public static void Greater(double arg1, double arg2)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Floats
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Greater(float arg1, float arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ public static void Greater(float arg1, float arg2)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region IComparables
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Greater(IComparable arg1, IComparable arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ public static void Greater(IComparable arg1, IComparable arg2)
+ {
+ Assert.That(arg1, Is.GreaterThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #endregion
+
+ #region Less
+
+ #region Ints
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Less(int arg1, int arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ public static void Less(int arg1, int arg2)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Unsigned Ints
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ //[CLSCompliant(false)]
+ public static void Less(uint arg1, uint arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ //[CLSCompliant(false)]
+ public static void Less(uint arg1, uint arg2)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Longs
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Less(long arg1, long arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ public static void Less(long arg1, long arg2)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Unsigned Longs
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ //[CLSCompliant(false)]
+ public static void Less(ulong arg1, ulong arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ //[CLSCompliant(false)]
+ public static void Less(ulong arg1, ulong arg2)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Decimals
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Less(decimal arg1, decimal arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ public static void Less(decimal arg1, decimal arg2)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Doubles
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Less(double arg1, double arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ public static void Less(double arg1, double arg2)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Floats
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Less(float arg1, float arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ public static void Less(float arg1, float arg2)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #region IComparables
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Less(IComparable arg1, IComparable arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ public static void Less(IComparable arg1, IComparable arg2)
+ {
+ Assert.That(arg1, Is.LessThan(arg2), null, null);
+ }
+
+ #endregion
+
+ #endregion
+
+ #region GreaterOrEqual
+
+ #region Ints
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void GreaterOrEqual(int arg1, int arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ public static void GreaterOrEqual(int arg1, int arg2)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Unsigned Ints
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ //[CLSCompliant(false)]
+ public static void GreaterOrEqual(uint arg1, uint arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ //[CLSCompliant(false)]
+ public static void GreaterOrEqual(uint arg1, uint arg2)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Longs
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void GreaterOrEqual(long arg1, long arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ public static void GreaterOrEqual(long arg1, long arg2)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Unsigned Longs
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ //[CLSCompliant(false)]
+ public static void GreaterOrEqual(ulong arg1, ulong arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ //[CLSCompliant(false)]
+ public static void GreaterOrEqual(ulong arg1, ulong arg2)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Decimals
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void GreaterOrEqual(decimal arg1, decimal arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ public static void GreaterOrEqual(decimal arg1, decimal arg2)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Doubles
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void GreaterOrEqual(double arg1, double arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ public static void GreaterOrEqual(double arg1, double arg2)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Floats
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void GreaterOrEqual(float arg1, float arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ public static void GreaterOrEqual(float arg1, float arg2)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region IComparables
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void GreaterOrEqual(IComparable arg1, IComparable arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is greater than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be greater</param>
+ /// <param name="arg2">The second value, expected to be less</param>
+ public static void GreaterOrEqual(IComparable arg1, IComparable arg2)
+ {
+ Assert.That(arg1, Is.GreaterThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #endregion
+
+ #region LessOrEqual
+
+ #region Ints
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void LessOrEqual(int arg1, int arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ public static void LessOrEqual(int arg1, int arg2)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Unsigned Ints
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ //[CLSCompliant(false)]
+ public static void LessOrEqual(uint arg1, uint arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ //[CLSCompliant(false)]
+ public static void LessOrEqual(uint arg1, uint arg2)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Longs
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void LessOrEqual(long arg1, long arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ public static void LessOrEqual(long arg1, long arg2)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Unsigned Longs
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ //[CLSCompliant(false)]
+ public static void LessOrEqual(ulong arg1, ulong arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ //[CLSCompliant(false)]
+ public static void LessOrEqual(ulong arg1, ulong arg2)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Decimals
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void LessOrEqual(decimal arg1, decimal arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ public static void LessOrEqual(decimal arg1, decimal arg2)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Doubles
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void LessOrEqual(double arg1, double arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ public static void LessOrEqual(double arg1, double arg2)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region Floats
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void LessOrEqual(float arg1, float arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ public static void LessOrEqual(float arg1, float arg2)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #region IComparables
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void LessOrEqual(IComparable arg1, IComparable arg2, string message, params object[] args)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the first value is less than or equal to the second
+ /// value. If it is not, then an
+ /// <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="arg1">The first value, expected to be less</param>
+ /// <param name="arg2">The second value, expected to be greater</param>
+ public static void LessOrEqual(IComparable arg1, IComparable arg2)
+ {
+ Assert.That(arg1, Is.LessThanOrEqualTo(arg2), null, null);
+ }
+
+ #endregion
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+
+using System.Collections;
+using NUnit.Framework.Constraints;
+
+namespace NUnit.Framework
+{
+ public partial class Assert
+ {
+ #region True
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void True(bool? condition, string message, params object[] args)
+ {
+ Assert.That(condition, Is.True ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void True(bool condition, string message, params object[] args)
+ {
+ Assert.That(condition, Is.True, message, args);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ public static void True(bool? condition)
+ {
+ Assert.That(condition, Is.True ,null, null);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ public static void True(bool condition)
+ {
+ Assert.That(condition, Is.True ,null, null);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsTrue(bool? condition, string message, params object[] args)
+ {
+ Assert.That(condition, Is.True ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsTrue(bool condition, string message, params object[] args)
+ {
+ Assert.That(condition, Is.True ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ public static void IsTrue(bool? condition)
+ {
+ Assert.That(condition, Is.True ,null, null);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ public static void IsTrue(bool condition)
+ {
+ Assert.That(condition, Is.True ,null, null);
+ }
+
+ #endregion
+
+ #region False
+
+ /// <summary>
+ /// Asserts that a condition is false. If the condition is true the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void False(bool? condition, string message, params object[] args)
+ {
+ Assert.That(condition, Is.False ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is false. If the condition is true the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void False(bool condition, string message, params object[] args)
+ {
+ Assert.That(condition, Is.False ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is false. If the condition is true the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ public static void False(bool? condition)
+ {
+ Assert.That(condition, Is.False ,null, null);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is false. If the condition is true the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ public static void False(bool condition)
+ {
+ Assert.That(condition, Is.False ,null, null);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is false. If the condition is true the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsFalse(bool? condition, string message, params object[] args)
+ {
+ Assert.That(condition, Is.False ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is false. If the condition is true the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsFalse(bool condition, string message, params object[] args)
+ {
+ Assert.That(condition, Is.False ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is false. If the condition is true the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ public static void IsFalse(bool? condition)
+ {
+ Assert.That(condition, Is.False ,null, null);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is false. If the condition is true the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ public static void IsFalse(bool condition)
+ {
+ Assert.That(condition, Is.False ,null, null);
+ }
+
+ #endregion
+
+ #region NotNull
+
+ /// <summary>
+ /// Verifies that the object that is passed in is not equal to <code>null</code>
+ /// If the object is <code>null</code> then an <see cref="AssertionException"/>
+ /// is thrown.
+ /// </summary>
+ /// <param name="anObject">The object that is to be tested</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void NotNull(object anObject, string message, params object[] args)
+ {
+ Assert.That(anObject, Is.Not.Null ,message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the object that is passed in is not equal to <code>null</code>
+ /// If the object is <code>null</code> then an <see cref="AssertionException"/>
+ /// is thrown.
+ /// </summary>
+ /// <param name="anObject">The object that is to be tested</param>
+ public static void NotNull(object anObject)
+ {
+ Assert.That(anObject, Is.Not.Null ,null, null);
+ }
+
+ /// <summary>
+ /// Verifies that the object that is passed in is not equal to <code>null</code>
+ /// If the object is <code>null</code> then an <see cref="AssertionException"/>
+ /// is thrown.
+ /// </summary>
+ /// <param name="anObject">The object that is to be tested</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsNotNull(object anObject, string message, params object[] args)
+ {
+ Assert.That(anObject, Is.Not.Null ,message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the object that is passed in is not equal to <code>null</code>
+ /// If the object is <code>null</code> then an <see cref="AssertionException"/>
+ /// is thrown.
+ /// </summary>
+ /// <param name="anObject">The object that is to be tested</param>
+ public static void IsNotNull(object anObject)
+ {
+ Assert.That(anObject, Is.Not.Null ,null, null);
+ }
+
+ #endregion
+
+ #region Null
+
+ /// <summary>
+ /// Verifies that the object that is passed in is equal to <code>null</code>
+ /// If the object is not <code>null</code> then an <see cref="AssertionException"/>
+ /// is thrown.
+ /// </summary>
+ /// <param name="anObject">The object that is to be tested</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Null(object anObject, string message, params object[] args)
+ {
+ Assert.That(anObject, Is.Null ,message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the object that is passed in is equal to <code>null</code>
+ /// If the object is not <code>null</code> then an <see cref="AssertionException"/>
+ /// is thrown.
+ /// </summary>
+ /// <param name="anObject">The object that is to be tested</param>
+ public static void Null(object anObject)
+ {
+ Assert.That(anObject, Is.Null ,null, null);
+ }
+
+ /// <summary>
+ /// Verifies that the object that is passed in is equal to <code>null</code>
+ /// If the object is not <code>null</code> then an <see cref="AssertionException"/>
+ /// is thrown.
+ /// </summary>
+ /// <param name="anObject">The object that is to be tested</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsNull(object anObject, string message, params object[] args)
+ {
+ Assert.That(anObject, Is.Null ,message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the object that is passed in is equal to <code>null</code>
+ /// If the object is not <code>null</code> then an <see cref="AssertionException"/>
+ /// is thrown.
+ /// </summary>
+ /// <param name="anObject">The object that is to be tested</param>
+ public static void IsNull(object anObject)
+ {
+ Assert.That(anObject, Is.Null ,null, null);
+ }
+
+ #endregion
+
+ #region IsNaN
+
+ /// <summary>
+ /// Verifies that the double that is passed in is an <code>NaN</code> value.
+ /// If the object is not <code>NaN</code> then an <see cref="AssertionException"/>
+ /// is thrown.
+ /// </summary>
+ /// <param name="aDouble">The value that is to be tested</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsNaN(double aDouble, string message, params object[] args)
+ {
+ Assert.That(aDouble, Is.NaN ,message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the double that is passed in is an <code>NaN</code> value.
+ /// If the object is not <code>NaN</code> then an <see cref="AssertionException"/>
+ /// is thrown.
+ /// </summary>
+ /// <param name="aDouble">The value that is to be tested</param>
+ public static void IsNaN(double aDouble)
+ {
+ Assert.That(aDouble, Is.NaN ,null, null);
+ }
+
+ /// <summary>
+ /// Verifies that the double that is passed in is an <code>NaN</code> value.
+ /// If the object is not <code>NaN</code> then an <see cref="AssertionException"/>
+ /// is thrown.
+ /// </summary>
+ /// <param name="aDouble">The value that is to be tested</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsNaN(double? aDouble, string message, params object[] args)
+ {
+ Assert.That(aDouble, Is.NaN ,message, args);
+ }
+
+ /// <summary>
+ /// Verifies that the double that is passed in is an <code>NaN</code> value.
+ /// If the object is not <code>NaN</code> then an <see cref="AssertionException"/>
+ /// is thrown.
+ /// </summary>
+ /// <param name="aDouble">The value that is to be tested</param>
+ public static void IsNaN(double? aDouble)
+ {
+ Assert.That(aDouble, Is.NaN ,null, null);
+ }
+
+ #endregion
+
+ #region IsEmpty
+
+ #region String
+
+ /// <summary>
+ /// Assert that a string is empty - that is equal to string.Empty
+ /// </summary>
+ /// <param name="aString">The string to be tested</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsEmpty(string aString, string message, params object[] args)
+ {
+ Assert.That(aString, new EmptyStringConstraint() ,message, args);
+ }
+
+ /// <summary>
+ /// Assert that a string is empty - that is equal to string.Empty
+ /// </summary>
+ /// <param name="aString">The string to be tested</param>
+ public static void IsEmpty(string aString)
+ {
+ Assert.That(aString, new EmptyStringConstraint() ,null, null);
+ }
+
+ #endregion
+
+ #region Collection
+
+ /// <summary>
+ /// Assert that an array, list or other collection is empty
+ /// </summary>
+ /// <param name="collection">An array, list or other collection implementing ICollection</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsEmpty(IEnumerable collection, string message, params object[] args)
+ {
+ Assert.That(collection, new EmptyCollectionConstraint() ,message, args);
+ }
+
+ /// <summary>
+ /// Assert that an array, list or other collection is empty
+ /// </summary>
+ /// <param name="collection">An array, list or other collection implementing ICollection</param>
+ public static void IsEmpty(IEnumerable collection)
+ {
+ Assert.That(collection, new EmptyCollectionConstraint() ,null, null);
+ }
+
+ #endregion
+
+ #endregion
+
+ #region IsNotEmpty
+
+ #region String
+
+ /// <summary>
+ /// Assert that a string is not empty - that is not equal to string.Empty
+ /// </summary>
+ /// <param name="aString">The string to be tested</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsNotEmpty(string aString, string message, params object[] args)
+ {
+ Assert.That(aString, Is.Not.Empty ,message, args);
+ }
+
+ /// <summary>
+ /// Assert that a string is not empty - that is not equal to string.Empty
+ /// </summary>
+ /// <param name="aString">The string to be tested</param>
+ public static void IsNotEmpty(string aString)
+ {
+ Assert.That(aString, Is.Not.Empty ,null, null);
+ }
+
+ #endregion
+
+ #region Collection
+
+ /// <summary>
+ /// Assert that an array, list or other collection is not empty
+ /// </summary>
+ /// <param name="collection">An array, list or other collection implementing ICollection</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsNotEmpty(IEnumerable collection, string message, params object[] args)
+ {
+ Assert.That(collection, Is.Not.Empty ,message, args);
+ }
+
+ /// <summary>
+ /// Assert that an array, list or other collection is not empty
+ /// </summary>
+ /// <param name="collection">An array, list or other collection implementing ICollection</param>
+ public static void IsNotEmpty(IEnumerable collection)
+ {
+ Assert.That(collection, Is.Not.Empty ,null, null);
+ }
+
+ #endregion
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+
+using System;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ public partial class Assert
+ {
+ #region AreEqual
+
+ #region Doubles
+
+ /// <summary>
+ /// Verifies that two doubles are equal considering a delta. If the
+ /// expected value is infinity then the delta value is ignored. If
+ /// they are not equal then an <see cref="AssertionException"/> is
+ /// thrown.
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ /// <param name="actual">The actual value</param>
+ /// <param name="delta">The maximum acceptable difference between the
+ /// the expected and the actual</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void AreEqual(double expected, double actual, double delta, string message, params object[] args)
+ {
+ AssertDoublesAreEqual(expected, actual, delta, message, args);
+ }
+
+ /// <summary>
+ /// Verifies that two doubles are equal considering a delta. If the
+ /// expected value is infinity then the delta value is ignored. If
+ /// they are not equal then an <see cref="AssertionException"/> is
+ /// thrown.
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ /// <param name="actual">The actual value</param>
+ /// <param name="delta">The maximum acceptable difference between the
+ /// the expected and the actual</param>
+ public static void AreEqual(double expected, double actual, double delta)
+ {
+ AssertDoublesAreEqual(expected, actual, delta, null, null);
+ }
+
+ /// <summary>
+ /// Verifies that two doubles are equal considering a delta. If the
+ /// expected value is infinity then the delta value is ignored. If
+ /// they are not equal then an <see cref="AssertionException"/> is
+ /// thrown.
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ /// <param name="actual">The actual value</param>
+ /// <param name="delta">The maximum acceptable difference between the
+ /// the expected and the actual</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void AreEqual(double expected, double? actual, double delta, string message, params object[] args)
+ {
+ AssertDoublesAreEqual(expected, (double)actual, delta, message, args);
+ }
+
+ /// <summary>
+ /// Verifies that two doubles are equal considering a delta. If the
+ /// expected value is infinity then the delta value is ignored. If
+ /// they are not equal then an <see cref="AssertionException"/> is
+ /// thrown.
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ /// <param name="actual">The actual value</param>
+ /// <param name="delta">The maximum acceptable difference between the
+ /// the expected and the actual</param>
+ public static void AreEqual(double expected, double? actual, double delta)
+ {
+ AssertDoublesAreEqual(expected, (double)actual, delta, null, null);
+ }
+
+ #endregion
+
+ #region Objects
+
+ /// <summary>
+ /// Verifies that two objects are equal. Two objects are considered
+ /// equal if both are null, or if both have the same value. NUnit
+ /// has special semantics for some object types.
+ /// If they are not equal an <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="expected">The value that is expected</param>
+ /// <param name="actual">The actual value</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void AreEqual(object expected, object actual, string message, params object[] args)
+ {
+ Assert.That(actual, Is.EqualTo(expected), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that two objects are equal. Two objects are considered
+ /// equal if both are null, or if both have the same value. NUnit
+ /// has special semantics for some object types.
+ /// If they are not equal an <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="expected">The value that is expected</param>
+ /// <param name="actual">The actual value</param>
+ public static void AreEqual(object expected, object actual)
+ {
+ Assert.That(actual, Is.EqualTo(expected), null, null);
+ }
+
+ #endregion
+
+ #endregion
+
+ #region AreNotEqual
+
+ #region Objects
+
+ /// <summary>
+ /// Verifies that two objects are not equal. Two objects are considered
+ /// equal if both are null, or if both have the same value. NUnit
+ /// has special semantics for some object types.
+ /// If they are equal an <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="expected">The value that is expected</param>
+ /// <param name="actual">The actual value</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void AreNotEqual(object expected, object actual, string message, params object[] args)
+ {
+ Assert.That(actual, Is.Not.EqualTo(expected), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that two objects are not equal. Two objects are considered
+ /// equal if both are null, or if both have the same value. NUnit
+ /// has special semantics for some object types.
+ /// If they are equal an <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="expected">The value that is expected</param>
+ /// <param name="actual">The actual value</param>
+ public static void AreNotEqual(object expected, object actual)
+ {
+ Assert.That(actual, Is.Not.EqualTo(expected), null, null);
+ }
+
+ #endregion
+
+ #endregion
+
+ #region AreSame
+
+ /// <summary>
+ /// Asserts that two objects refer to the same object. If they
+ /// are not the same an <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="expected">The expected object</param>
+ /// <param name="actual">The actual object</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void AreSame(object expected, object actual, string message, params object[] args)
+ {
+ Assert.That(actual, Is.SameAs(expected), message, args);
+ }
+
+ /// <summary>
+ /// Asserts that two objects refer to the same object. If they
+ /// are not the same an <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="expected">The expected object</param>
+ /// <param name="actual">The actual object</param>
+ public static void AreSame(object expected, object actual)
+ {
+ Assert.That(actual, Is.SameAs(expected), null, null);
+ }
+
+ #endregion
+
+ #region AreNotSame
+
+ /// <summary>
+ /// Asserts that two objects do not refer to the same object. If they
+ /// are the same an <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="expected">The expected object</param>
+ /// <param name="actual">The actual object</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void AreNotSame(object expected, object actual, string message, params object[] args)
+ {
+ Assert.That(actual, Is.Not.SameAs(expected), message, args);
+ }
+
+ /// <summary>
+ /// Asserts that two objects do not refer to the same object. If they
+ /// are the same an <see cref="AssertionException"/> is thrown.
+ /// </summary>
+ /// <param name="expected">The expected object</param>
+ /// <param name="actual">The actual object</param>
+ public static void AreNotSame(object expected, object actual)
+ {
+ Assert.That(actual, Is.Not.SameAs(expected), null, null);
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ /// <summary>
+ /// Helper for Assert.AreEqual(double expected, double actual, ...)
+ /// allowing code generation to work consistently.
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ /// <param name="actual">The actual value</param>
+ /// <param name="delta">The maximum acceptable difference between the
+ /// the expected and the actual</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ protected static void AssertDoublesAreEqual(double expected, double actual, double delta, string message, object[] args)
+ {
+ if (double.IsNaN(expected) || double.IsInfinity(expected))
+ Assert.That(actual, Is.EqualTo(expected), message, args);
+ else
+ Assert.That(actual, Is.EqualTo(expected).Within(delta), message, args);
+ }
+
+ private static void IncrementAssertCount()
+ {
+ TestExecutionContext.CurrentContext.IncrementAssertCount();
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if NET_4_0 || NET_4_5 || PORTABLE
+using System;
+using NUnit.Framework.Constraints;
+using NUnit.Framework.Internal;
+
+
+namespace NUnit.Framework
+{
+ public partial class Assert
+ {
+ #region ThrowsAsync
+
+ /// <summary>
+ /// Verifies that an async delegate throws a particular exception when called.
+ /// </summary>
+ /// <param name="expression">A constraint to be satisfied by the exception</param>
+ /// <param name="code">A TestSnippet delegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static Exception ThrowsAsync(IResolveConstraint expression, AsyncTestDelegate code, string message, params object[] args)
+ {
+ Exception caughtException = null;
+ using (var region = AsyncInvocationRegion.Create(code))
+ {
+ try
+ {
+ var task = code();
+ region.WaitForPendingOperationsToComplete(task);
+ }
+ catch (Exception e)
+ {
+ caughtException = e;
+ }
+ }
+
+ Assert.That(caughtException, expression, message, args);
+
+ return caughtException;
+ }
+
+ /// <summary>
+ /// Verifies that an async delegate throws a particular exception when called.
+ /// </summary>
+ /// <param name="expression">A constraint to be satisfied by the exception</param>
+ /// <param name="code">A TestSnippet delegate</param>
+ public static Exception ThrowsAsync(IResolveConstraint expression, AsyncTestDelegate code)
+ {
+ return ThrowsAsync(expression, code, string.Empty, null);
+ }
+
+ /// <summary>
+ /// Verifies that an async delegate throws a particular exception when called.
+ /// </summary>
+ /// <param name="expectedExceptionType">The exception Type expected</param>
+ /// <param name="code">A TestDelegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static Exception ThrowsAsync(Type expectedExceptionType, AsyncTestDelegate code, string message, params object[] args)
+ {
+ return ThrowsAsync(new ExceptionTypeConstraint(expectedExceptionType), code, message, args);
+ }
+
+ /// <summary>
+ /// Verifies that an async delegate throws a particular exception when called.
+ /// </summary>
+ /// <param name="expectedExceptionType">The exception Type expected</param>
+ /// <param name="code">A TestDelegate</param>
+ public static Exception ThrowsAsync(Type expectedExceptionType, AsyncTestDelegate code)
+ {
+ return ThrowsAsync(new ExceptionTypeConstraint(expectedExceptionType), code, string.Empty, null);
+ }
+
+ #endregion
+
+ #region ThrowsAsync<TActual>
+
+ /// <summary>
+ /// Verifies that an async delegate throws a particular exception when called.
+ /// </summary>
+ /// <typeparam name="TActual">Type of the expected exception</typeparam>
+ /// <param name="code">A TestDelegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static TActual ThrowsAsync<TActual>(AsyncTestDelegate code, string message, params object[] args) where TActual : Exception
+ {
+ return (TActual)ThrowsAsync(typeof (TActual), code, message, args);
+ }
+
+ /// <summary>
+ /// Verifies that an async delegate throws a particular exception when called.
+ /// </summary>
+ /// <typeparam name="TActual">Type of the expected exception</typeparam>
+ /// <param name="code">A TestDelegate</param>
+ public static TActual ThrowsAsync<TActual>(AsyncTestDelegate code) where TActual : Exception
+ {
+ return ThrowsAsync<TActual>(code, string.Empty, null);
+ }
+
+ #endregion
+
+ #region CatchAsync
+
+ /// <summary>
+ /// Verifies that an async delegate throws an exception when called
+ /// and returns it.
+ /// </summary>
+ /// <param name="code">A TestDelegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static Exception CatchAsync(AsyncTestDelegate code, string message, params object[] args)
+ {
+ return ThrowsAsync(new InstanceOfTypeConstraint(typeof(Exception)), code, message, args);
+ }
+
+ /// <summary>
+ /// Verifies that an async delegate throws an exception when called
+ /// and returns it.
+ /// </summary>
+ /// <param name="code">A TestDelegate</param>
+ public static Exception CatchAsync(AsyncTestDelegate code)
+ {
+ return ThrowsAsync(new InstanceOfTypeConstraint(typeof(Exception)), code);
+ }
+
+ /// <summary>
+ /// Verifies that an async delegate throws an exception of a certain Type
+ /// or one derived from it when called and returns it.
+ /// </summary>
+ /// <param name="expectedExceptionType">The expected Exception Type</param>
+ /// <param name="code">A TestDelegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static Exception CatchAsync(Type expectedExceptionType, AsyncTestDelegate code, string message, params object[] args)
+ {
+ return ThrowsAsync(new InstanceOfTypeConstraint(expectedExceptionType), code, message, args);
+ }
+
+ /// <summary>
+ /// Verifies that an async delegate throws an exception of a certain Type
+ /// or one derived from it when called and returns it.
+ /// </summary>
+ /// <param name="expectedExceptionType">The expected Exception Type</param>
+ /// <param name="code">A TestDelegate</param>
+ public static Exception CatchAsync(Type expectedExceptionType, AsyncTestDelegate code)
+ {
+ return ThrowsAsync(new InstanceOfTypeConstraint(expectedExceptionType), code);
+ }
+
+ #endregion
+
+ #region CatchAsync<TActual>
+
+ /// <summary>
+ /// Verifies that an async delegate throws an exception of a certain Type
+ /// or one derived from it when called and returns it.
+ /// </summary>
+ /// <param name="code">A TestDelegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static TActual CatchAsync<TActual>(AsyncTestDelegate code, string message, params object[] args) where TActual : Exception
+ {
+ return (TActual)ThrowsAsync(new InstanceOfTypeConstraint(typeof (TActual)), code, message, args);
+ }
+
+ /// <summary>
+ /// Verifies that an async delegate throws an exception of a certain Type
+ /// or one derived from it when called and returns it.
+ /// </summary>
+ /// <param name="code">A TestDelegate</param>
+ public static TActual CatchAsync<TActual>(AsyncTestDelegate code) where TActual : Exception
+ {
+ return (TActual)ThrowsAsync(new InstanceOfTypeConstraint(typeof (TActual)), code);
+ }
+
+ #endregion
+
+ #region DoesNotThrowAsync
+
+ /// <summary>
+ /// Verifies that an async delegate does not throw an exception
+ /// </summary>
+ /// <param name="code">A TestDelegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static void DoesNotThrowAsync(AsyncTestDelegate code, string message, params object[] args)
+ {
+ Assert.That(code, new ThrowsNothingConstraint(), message, args);
+ }
+ /// <summary>
+ /// Verifies that an async delegate does not throw an exception.
+ /// </summary>
+ /// <param name="code">A TestDelegate</param>
+ public static void DoesNotThrowAsync(AsyncTestDelegate code)
+ {
+ DoesNotThrowAsync(code, string.Empty, null);
+ }
+
+ #endregion
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+
+using System;
+using NUnit.Framework.Constraints;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ public partial class Assert
+ {
+ #region Throws
+ /// <summary>
+ /// Verifies that a delegate throws a particular exception when called.
+ /// </summary>
+ /// <param name="expression">A constraint to be satisfied by the exception</param>
+ /// <param name="code">A TestSnippet delegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static Exception Throws(IResolveConstraint expression, TestDelegate code, string message, params object[] args)
+ {
+ Exception caughtException = null;
+
+#if NET_4_0 || NET_4_5 || PORTABLE
+ if (AsyncInvocationRegion.IsAsyncOperation(code))
+ {
+ using (var region = AsyncInvocationRegion.Create(code))
+ {
+ code();
+
+ try
+ {
+ region.WaitForPendingOperationsToComplete(null);
+ }
+ catch (Exception e)
+ {
+ caughtException = e;
+ }
+ }
+ }
+ else
+#endif
+ try
+ {
+ code();
+ }
+ catch (Exception ex)
+ {
+ caughtException = ex;
+ }
+
+ Assert.That(caughtException, expression, message, args);
+
+ return caughtException;
+ }
+
+ /// <summary>
+ /// Verifies that a delegate throws a particular exception when called.
+ /// </summary>
+ /// <param name="expression">A constraint to be satisfied by the exception</param>
+ /// <param name="code">A TestSnippet delegate</param>
+ public static Exception Throws(IResolveConstraint expression, TestDelegate code)
+ {
+ return Throws(expression, code, string.Empty, null);
+ }
+
+ /// <summary>
+ /// Verifies that a delegate throws a particular exception when called.
+ /// </summary>
+ /// <param name="expectedExceptionType">The exception Type expected</param>
+ /// <param name="code">A TestDelegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static Exception Throws(Type expectedExceptionType, TestDelegate code, string message, params object[] args)
+ {
+ return Throws(new ExceptionTypeConstraint(expectedExceptionType), code, message, args);
+ }
+
+ /// <summary>
+ /// Verifies that a delegate throws a particular exception when called.
+ /// </summary>
+ /// <param name="expectedExceptionType">The exception Type expected</param>
+ /// <param name="code">A TestDelegate</param>
+ public static Exception Throws(Type expectedExceptionType, TestDelegate code)
+ {
+ return Throws(new ExceptionTypeConstraint(expectedExceptionType), code, string.Empty, null);
+ }
+
+ #endregion
+
+ #region Throws<TActual>
+
+ /// <summary>
+ /// Verifies that a delegate throws a particular exception when called.
+ /// </summary>
+ /// <typeparam name="TActual">Type of the expected exception</typeparam>
+ /// <param name="code">A TestDelegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static TActual Throws<TActual>(TestDelegate code, string message, params object[] args) where TActual : Exception
+ {
+ return (TActual)Throws(typeof(TActual), code, message, args);
+ }
+
+ /// <summary>
+ /// Verifies that a delegate throws a particular exception when called.
+ /// </summary>
+ /// <typeparam name="TActual">Type of the expected exception</typeparam>
+ /// <param name="code">A TestDelegate</param>
+ public static TActual Throws<TActual>(TestDelegate code) where TActual : Exception
+ {
+ return Throws<TActual>(code, string.Empty, null);
+ }
+
+ #endregion
+
+ #region Catch
+ /// <summary>
+ /// Verifies that a delegate throws an exception when called
+ /// and returns it.
+ /// </summary>
+ /// <param name="code">A TestDelegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static Exception Catch(TestDelegate code, string message, params object[] args)
+ {
+ return Throws(new InstanceOfTypeConstraint(typeof(Exception)), code, message, args);
+ }
+
+ /// <summary>
+ /// Verifies that a delegate throws an exception when called
+ /// and returns it.
+ /// </summary>
+ /// <param name="code">A TestDelegate</param>
+ public static Exception Catch(TestDelegate code)
+ {
+ return Throws(new InstanceOfTypeConstraint(typeof(Exception)), code);
+ }
+
+ /// <summary>
+ /// Verifies that a delegate throws an exception of a certain Type
+ /// or one derived from it when called and returns it.
+ /// </summary>
+ /// <param name="expectedExceptionType">The expected Exception Type</param>
+ /// <param name="code">A TestDelegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static Exception Catch(Type expectedExceptionType, TestDelegate code, string message, params object[] args)
+ {
+ return Throws(new InstanceOfTypeConstraint(expectedExceptionType), code, message, args);
+ }
+
+ /// <summary>
+ /// Verifies that a delegate throws an exception of a certain Type
+ /// or one derived from it when called and returns it.
+ /// </summary>
+ /// <param name="expectedExceptionType">The expected Exception Type</param>
+ /// <param name="code">A TestDelegate</param>
+ public static Exception Catch(Type expectedExceptionType, TestDelegate code)
+ {
+ return Throws(new InstanceOfTypeConstraint(expectedExceptionType), code);
+ }
+ #endregion
+
+ #region Catch<TActual>
+
+ /// <summary>
+ /// Verifies that a delegate throws an exception of a certain Type
+ /// or one derived from it when called and returns it.
+ /// </summary>
+ /// <param name="code">A TestDelegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static TActual Catch<TActual>(TestDelegate code, string message, params object[] args) where TActual : System.Exception
+ {
+ return (TActual)Throws(new InstanceOfTypeConstraint(typeof(TActual)), code, message, args);
+ }
+
+ /// <summary>
+ /// Verifies that a delegate throws an exception of a certain Type
+ /// or one derived from it when called and returns it.
+ /// </summary>
+ /// <param name="code">A TestDelegate</param>
+ public static TActual Catch<TActual>(TestDelegate code) where TActual : System.Exception
+ {
+ return (TActual)Throws(new InstanceOfTypeConstraint(typeof(TActual)), code);
+ }
+
+ #endregion
+
+ #region DoesNotThrow
+
+ /// <summary>
+ /// Verifies that a delegate does not throw an exception
+ /// </summary>
+ /// <param name="code">A TestDelegate</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public static void DoesNotThrow(TestDelegate code, string message, params object[] args)
+ {
+ Assert.That(code, new ThrowsNothingConstraint(), message, args);
+ }
+
+ /// <summary>
+ /// Verifies that a delegate does not throw an exception.
+ /// </summary>
+ /// <param name="code">A TestDelegate</param>
+ public static void DoesNotThrow(TestDelegate code)
+ {
+ DoesNotThrow(code, string.Empty, null);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+
+using System;
+using NUnit.Framework.Constraints;
+using NUnit.Framework.Internal;
+using NUnit.Framework.TUnit;
+
+namespace NUnit.Framework
+{
+ public partial class Assert
+ {
+ #region Assert.That
+
+ #region Boolean
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ /// <param name="message">The message to display if the condition is false</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ static public void That(bool condition, string message, params object[] args)
+ {
+ Assert.That(condition, Is.True, message, args);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ static public void That(bool condition)
+ {
+ Assert.That(condition, Is.True, null, null);
+ }
+
+ #endregion
+
+ #region Lambda returning Boolean
+#if !NET_2_0
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">A lambda that returns a Boolean</param>
+ /// <param name="message">The message to display if the condition is false</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ static public void That(Func<bool> condition, string message, params object[] args)
+ {
+ Assert.That(condition.Invoke(), Is.True, message, args);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>.
+ /// </summary>
+ /// <param name="condition">A lambda that returns a Boolean</param>
+ static public void That(Func<bool> condition)
+ {
+ Assert.That(condition.Invoke(), Is.True, null, null);
+ }
+#endif
+ #endregion
+
+ #region ActualValueDelegate
+
+ /// <summary>
+ /// Apply a constraint to an actual value, succeeding if the constraint
+ /// is satisfied and throwing an assertion exception on failure.
+ /// </summary>
+ /// <param name="expr">A Constraint expression to be applied</param>
+ /// <param name="del">An ActualValueDelegate returning the value to be tested</param>
+ static public void That<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr)
+ {
+ Assert.That(del, expr.Resolve(), null, null);
+ }
+
+ /// <summary>
+ /// Apply a constraint to an actual value, succeeding if the constraint
+ /// is satisfied and throwing an assertion exception on failure.
+ /// </summary>
+ /// <param name="del">An ActualValueDelegate returning the value to be tested</param>
+ /// <param name="expr">A Constraint expression to be applied</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ static public void That<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, string message, params object[] args)
+ {
+ var constraint = expr.Resolve();
+
+ IncrementAssertCount();
+ var result = constraint.ApplyTo(del);
+ if (!result.IsSuccess)
+ {
+ MessageWriter writer = new TextMessageWriter(message, args);
+ result.WriteMessageTo(writer);
+ throw new AssertionException(writer.ToString());
+ }
+ }
+
+ #endregion
+
+ #region TestDelegate
+
+ /// <summary>
+ /// Asserts that the code represented by a delegate throws an exception
+ /// that satisfies the constraint provided.
+ /// </summary>
+ /// <param name="code">A TestDelegate to be executed</param>
+ /// <param name="constraint">A ThrowsConstraint used in the test</param>
+ static public void That(TestDelegate code, IResolveConstraint constraint)
+ {
+ Assert.That(code, constraint, null, null);
+ }
+
+ /// <summary>
+ /// Asserts that the code represented by a delegate throws an exception
+ /// that satisfies the constraint provided.
+ /// </summary>
+ /// <param name="code">A TestDelegate to be executed</param>
+ /// <param name="constraint">A ThrowsConstraint used in the test</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ static public void That(TestDelegate code, IResolveConstraint constraint, string message, params string[] args)
+ {
+ Assert.That((object)code, constraint, message, args);
+ }
+
+ #endregion
+
+ #endregion
+
+ #region Assert.That<TActual>
+
+ /// <summary>
+ /// Apply a constraint to an actual value, succeeding if the constraint
+ /// is satisfied and throwing an assertion exception on failure.
+ /// </summary>
+ /// <param name="expression">A Constraint to be applied</param>
+ /// <param name="actual">The actual value to test</param>
+ static public void That<TActual>(TActual actual, IResolveConstraint expression)
+ {
+ Assert.That(actual, expression, null, null);
+ }
+
+ /// <summary>
+ /// Apply a constraint to an actual value, succeeding if the constraint
+ /// is satisfied and throwing an assertion exception on failure.
+ /// </summary>
+ /// <param name="expression">A Constraint expression to be applied</param>
+ /// <param name="actual">The actual value to test</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ static public void That<TActual>(TActual actual, IResolveConstraint expression, string message, params object[] args)
+ {
+ var constraint = expression.Resolve();
+
+ IncrementAssertCount();
+ var result = constraint.ApplyTo(actual);
+ if (!result.IsSuccess)
+ {
+ // [DuongNT][BEGIN]: Write console logs
+ TLogger.Write(message);
+ // [DuongNT][END]: Write console logs
+
+ MessageWriter writer = new TextMessageWriter(message, args);
+ result.WriteMessageTo(writer);
+ throw new AssertionException(writer.ToString());
+ }
+ }
+
+ #endregion
+
+ #region Assert.ByVal
+
+ /// <summary>
+ /// Apply a constraint to an actual value, succeeding if the constraint
+ /// is satisfied and throwing an assertion exception on failure.
+ /// Used as a synonym for That in rare cases where a private setter
+ /// causes a Visual Basic compilation error.
+ /// </summary>
+ /// <param name="expression">A Constraint to be applied</param>
+ /// <param name="actual">The actual value to test</param>
+ static public void ByVal(object actual, IResolveConstraint expression)
+ {
+ Assert.That(actual, expression, null, null);
+ }
+
+ /// <summary>
+ /// Apply a constraint to an actual value, succeeding if the constraint
+ /// is satisfied and throwing an assertion exception on failure.
+ /// Used as a synonym for That in rare cases where a private setter
+ /// causes a Visual Basic compilation error.
+ /// </summary>
+ /// <remarks>
+ /// This method is provided for use by VB developers needing to test
+ /// the value of properties with private setters.
+ /// </remarks>
+ /// <param name="expression">A Constraint expression to be applied</param>
+ /// <param name="actual">The actual value to test</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ static public void ByVal(object actual, IResolveConstraint expression, string message, params object[] args)
+ {
+ Assert.That(actual, expression, message, args);
+ }
+
+ #endregion
+
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+
+using System;
+
+namespace NUnit.Framework
+{
+ public partial class Assert
+ {
+ #region IsAssignableFrom
+
+ /// <summary>
+ /// Asserts that an object may be assigned a value of a given Type.
+ /// </summary>
+ /// <param name="expected">The expected Type.</param>
+ /// <param name="actual">The object under examination</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsAssignableFrom(Type expected, object actual, string message, params object[] args)
+ {
+ Assert.That(actual, Is.AssignableFrom(expected) ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that an object may be assigned a value of a given Type.
+ /// </summary>
+ /// <param name="expected">The expected Type.</param>
+ /// <param name="actual">The object under examination</param>
+ public static void IsAssignableFrom(Type expected, object actual)
+ {
+ Assert.That(actual, Is.AssignableFrom(expected) ,null, null);
+ }
+
+ #endregion
+
+ #region IsAssignableFrom<TExpected>
+
+ /// <summary>
+ /// Asserts that an object may be assigned a value of a given Type.
+ /// </summary>
+ /// <typeparam name="TExpected">The expected Type.</typeparam>
+ /// <param name="actual">The object under examination</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsAssignableFrom<TExpected>(object actual, string message, params object[] args)
+ {
+ Assert.That(actual, Is.AssignableFrom(typeof(TExpected)) ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that an object may be assigned a value of a given Type.
+ /// </summary>
+ /// <typeparam name="TExpected">The expected Type.</typeparam>
+ /// <param name="actual">The object under examination</param>
+ public static void IsAssignableFrom<TExpected>(object actual)
+ {
+ Assert.That(actual, Is.AssignableFrom(typeof(TExpected)) ,null, null);
+ }
+
+ #endregion
+
+ #region IsNotAssignableFrom
+
+ /// <summary>
+ /// Asserts that an object may not be assigned a value of a given Type.
+ /// </summary>
+ /// <param name="expected">The expected Type.</param>
+ /// <param name="actual">The object under examination</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsNotAssignableFrom(Type expected, object actual, string message, params object[] args)
+ {
+ Assert.That(actual, Is.Not.AssignableFrom(expected) ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that an object may not be assigned a value of a given Type.
+ /// </summary>
+ /// <param name="expected">The expected Type.</param>
+ /// <param name="actual">The object under examination</param>
+ public static void IsNotAssignableFrom(Type expected, object actual)
+ {
+ Assert.That(actual, Is.Not.AssignableFrom(expected) ,null, null);
+ }
+
+ #endregion
+
+ #region IsNotAssignableFrom<TExpected>
+
+ /// <summary>
+ /// Asserts that an object may not be assigned a value of a given Type.
+ /// </summary>
+ /// <typeparam name="TExpected">The expected Type.</typeparam>
+ /// <param name="actual">The object under examination</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsNotAssignableFrom<TExpected>(object actual, string message, params object[] args)
+ {
+ Assert.That(actual, Is.Not.AssignableFrom(typeof(TExpected)) ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that an object may not be assigned a value of a given Type.
+ /// </summary>
+ /// <typeparam name="TExpected">The expected Type.</typeparam>
+ /// <param name="actual">The object under examination</param>
+ public static void IsNotAssignableFrom<TExpected>(object actual)
+ {
+ Assert.That(actual, Is.Not.AssignableFrom(typeof(TExpected)) ,null, null);
+ }
+
+ #endregion
+
+ #region IsInstanceOf
+
+ /// <summary>
+ /// Asserts that an object is an instance of a given type.
+ /// </summary>
+ /// <param name="expected">The expected Type</param>
+ /// <param name="actual">The object being examined</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsInstanceOf(Type expected, object actual, string message, params object[] args)
+ {
+ Assert.That(actual, Is.InstanceOf(expected) ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that an object is an instance of a given type.
+ /// </summary>
+ /// <param name="expected">The expected Type</param>
+ /// <param name="actual">The object being examined</param>
+ public static void IsInstanceOf(Type expected, object actual)
+ {
+ Assert.That(actual, Is.InstanceOf(expected) ,null, null);
+ }
+
+ #endregion
+
+ #region IsInstanceOf<TExpected>
+
+ /// <summary>
+ /// Asserts that an object is an instance of a given type.
+ /// </summary>
+ /// <typeparam name="TExpected">The expected Type</typeparam>
+ /// <param name="actual">The object being examined</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsInstanceOf<TExpected>(object actual, string message, params object[] args)
+ {
+ Assert.That(actual, Is.InstanceOf(typeof(TExpected)) ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that an object is an instance of a given type.
+ /// </summary>
+ /// <typeparam name="TExpected">The expected Type</typeparam>
+ /// <param name="actual">The object being examined</param>
+ public static void IsInstanceOf<TExpected>(object actual)
+ {
+ Assert.That(actual, Is.InstanceOf(typeof(TExpected)) ,null, null);
+ }
+
+ #endregion
+
+ #region IsNotInstanceOf
+
+ /// <summary>
+ /// Asserts that an object is not an instance of a given type.
+ /// </summary>
+ /// <param name="expected">The expected Type</param>
+ /// <param name="actual">The object being examined</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsNotInstanceOf(Type expected, object actual, string message, params object[] args)
+ {
+ Assert.That(actual, Is.Not.InstanceOf(expected) ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that an object is not an instance of a given type.
+ /// </summary>
+ /// <param name="expected">The expected Type</param>
+ /// <param name="actual">The object being examined</param>
+ public static void IsNotInstanceOf(Type expected, object actual)
+ {
+ Assert.That(actual, Is.Not.InstanceOf(expected) ,null, null);
+ }
+
+ #endregion
+
+ #region IsNotInstanceOf<TExpected>
+
+ /// <summary>
+ /// Asserts that an object is not an instance of a given type.
+ /// </summary>
+ /// <typeparam name="TExpected">The expected Type</typeparam>
+ /// <param name="actual">The object being examined</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void IsNotInstanceOf<TExpected>(object actual, string message, params object[] args)
+ {
+ Assert.That(actual, Is.Not.InstanceOf(typeof(TExpected)) ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that an object is not an instance of a given type.
+ /// </summary>
+ /// <typeparam name="TExpected">The expected Type</typeparam>
+ /// <param name="actual">The object being examined</param>
+ public static void IsNotInstanceOf<TExpected>(object actual)
+ {
+ Assert.That(actual, Is.Not.InstanceOf(typeof(TExpected)) ,null, null);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.ComponentModel;
+using NUnit.Framework.Constraints;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Delegate used by tests that execute code and
+ /// capture any thrown exception.
+ /// </summary>
+ public delegate void TestDelegate();
+
+#if NET_4_0 || NET_4_5 || PORTABLE
+ /// <summary>
+ /// Delegate used by tests that execute async code and
+ /// capture any thrown exception.
+ /// </summary>
+ public delegate System.Threading.Tasks.Task AsyncTestDelegate();
+#endif
+
+ /// <summary>
+ /// The Assert class contains a collection of static methods that
+ /// implement the most common assertions used in NUnit.
+ /// </summary>
+ public partial class Assert
+ {
+ #region Constructor
+
+ /// <summary>
+ /// We don't actually want any instances of this object, but some people
+ /// like to inherit from it to add other static methods. Hence, the
+ /// protected constructor disallows any instances of this object.
+ /// </summary>
+ protected Assert() { }
+
+ #endregion
+
+ #region Equals and ReferenceEquals
+
+ /// <summary>
+ /// The Equals method throws an InvalidOperationException. This is done
+ /// to make sure there is no mistake by calling this function.
+ /// </summary>
+ /// <param name="a"></param>
+ /// <param name="b"></param>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static new bool Equals(object a, object b)
+ {
+ throw new InvalidOperationException("Assert.Equals should not be used for Assertions");
+ }
+
+ /// <summary>
+ /// override the default ReferenceEquals to throw an InvalidOperationException. This
+ /// implementation makes sure there is no mistake in calling this function
+ /// as part of Assert.
+ /// </summary>
+ /// <param name="a"></param>
+ /// <param name="b"></param>
+ public static new void ReferenceEquals(object a, object b)
+ {
+ throw new InvalidOperationException("Assert.ReferenceEquals should not be used for Assertions");
+ }
+
+ #endregion
+
+ #region Pass
+
+ /// <summary>
+ /// Throws a <see cref="SuccessException"/> with the message and arguments
+ /// that are passed in. This allows a test to be cut short, with a result
+ /// of success returned to NUnit.
+ /// </summary>
+ /// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ static public void Pass(string message, params object[] args)
+ {
+ if (message == null) message = string.Empty;
+ else if (args != null && args.Length > 0)
+ message = string.Format(message, args);
+
+ //throw new SuccessException(message);
+ }
+
+ /// <summary>
+ /// Throws a <see cref="SuccessException"/> with the message and arguments
+ /// that are passed in. This allows a test to be cut short, with a result
+ /// of success returned to NUnit.
+ /// </summary>
+ /// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
+ static public void Pass(string message)
+ {
+ Assert.Pass(message, null);
+ }
+
+ /// <summary>
+ /// Throws a <see cref="SuccessException"/> with the message and arguments
+ /// that are passed in. This allows a test to be cut short, with a result
+ /// of success returned to NUnit.
+ /// </summary>
+ static public void Pass()
+ {
+ Assert.Pass(string.Empty, null);
+ }
+
+ #endregion
+
+ #region Fail
+
+ /// <summary>
+ /// Throws an <see cref="AssertionException"/> with the message and arguments
+ /// that are passed in. This is used by the other Assert functions.
+ /// </summary>
+ /// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ static public void Fail(string message, params object[] args)
+ {
+ if (message == null) message = string.Empty;
+ else if (args != null && args.Length > 0)
+ message = string.Format(message, args);
+
+ throw new AssertionException(message);
+ }
+
+ /// <summary>
+ /// Throws an <see cref="AssertionException"/> with the message that is
+ /// passed in. This is used by the other Assert functions.
+ /// </summary>
+ /// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
+ static public void Fail(string message)
+ {
+ Assert.Fail(message, null);
+ }
+
+ /// <summary>
+ /// Throws an <see cref="AssertionException"/>.
+ /// This is used by the other Assert functions.
+ /// </summary>
+ static public void Fail()
+ {
+ Assert.Fail(string.Empty, null);
+ }
+
+ #endregion
+
+ #region Ignore
+
+ /// <summary>
+ /// Throws an <see cref="IgnoreException"/> with the message and arguments
+ /// that are passed in. This causes the test to be reported as ignored.
+ /// </summary>
+ /// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ static public void Ignore(string message, params object[] args)
+ {
+ if (message == null) message = string.Empty;
+ else if (args != null && args.Length > 0)
+ message = string.Format(message, args);
+
+ throw new IgnoreException(message);
+ }
+
+ /// <summary>
+ /// Throws an <see cref="IgnoreException"/> with the message that is
+ /// passed in. This causes the test to be reported as ignored.
+ /// </summary>
+ /// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
+ static public void Ignore(string message)
+ {
+ Assert.Ignore(message, null);
+ }
+
+ /// <summary>
+ /// Throws an <see cref="IgnoreException"/>.
+ /// This causes the test to be reported as ignored.
+ /// </summary>
+ static public void Ignore()
+ {
+ Assert.Ignore(string.Empty, null);
+ }
+
+ #endregion
+
+ #region InConclusive
+
+ /// <summary>
+ /// Throws an <see cref="InconclusiveException"/> with the message and arguments
+ /// that are passed in. This causes the test to be reported as inconclusive.
+ /// </summary>
+ /// <param name="message">The message to initialize the <see cref="InconclusiveException"/> with.</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ static public void Inconclusive(string message, params object[] args)
+ {
+ if (message == null) message = string.Empty;
+ else if (args != null && args.Length > 0)
+ message = string.Format(message, args);
+
+ throw new InconclusiveException(message);
+ }
+
+ /// <summary>
+ /// Throws an <see cref="InconclusiveException"/> with the message that is
+ /// passed in. This causes the test to be reported as inconclusive.
+ /// </summary>
+ /// <param name="message">The message to initialize the <see cref="InconclusiveException"/> with.</param>
+ static public void Inconclusive(string message)
+ {
+ Assert.Inconclusive(message, null);
+ }
+
+ /// <summary>
+ /// Throws an <see cref="InconclusiveException"/>.
+ /// This causes the test to be reported as Inconclusive.
+ /// </summary>
+ static public void Inconclusive()
+ {
+ Assert.Inconclusive(string.Empty, null);
+ }
+
+ #endregion
+
+ #region Contains
+
+ /// <summary>
+ /// Asserts that an object is contained in a list.
+ /// </summary>
+ /// <param name="expected">The expected object</param>
+ /// <param name="actual">The list to be examined</param>
+ /// <param name="message">The message to display in case of failure</param>
+ /// <param name="args">Array of objects to be used in formatting the message</param>
+ public static void Contains(object expected, ICollection actual, string message, params object[] args)
+ {
+ Assert.That(actual, new CollectionContainsConstraint(expected) ,message, args);
+ }
+
+ /// <summary>
+ /// Asserts that an object is contained in a list.
+ /// </summary>
+ /// <param name="expected">The expected object</param>
+ /// <param name="actual">The list to be examined</param>
+ public static void Contains(object expected, ICollection actual)
+ {
+ Assert.That(actual, new CollectionContainsConstraint(expected) ,null, null);
+ }
+
+ #endregion
+
+ #region Multiple
+
+ ///// <summary>
+ ///// If an assert fails within this block, execution will continue and
+ ///// the errors will be reported at the end of the block.
+ ///// </summary>
+ ///// <param name="del">The test delegate</param>
+ //public static void Multiple(TestDelegate del)
+ //{
+ // del();
+ //}
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections;
+using NUnit.Framework.Constraints;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// AssertionHelper is an optional base class for user tests,
+ /// allowing the use of shorter ids for constraints and
+ /// asserts and avoiding conflict with the definition of
+ /// <see cref="Is"/>, from which it inherits much of its
+ /// behavior, in certain mock object frameworks.
+ /// </summary>
+ public class AssertionHelper : ConstraintFactory
+ {
+ #region Expect
+
+ #region Boolean
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>. Works Identically to
+ /// <see cref="Assert.That(bool, string, object[])"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ /// <param name="message">The message to display if the condition is false</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public void Expect(bool condition, string message, params object[] args)
+ {
+ Assert.That(condition, Is.True, message, args);
+ }
+
+ /// <summary>
+ /// Asserts that a condition is true. If the condition is false the method throws
+ /// an <see cref="AssertionException"/>. Works Identically to <see cref="Assert.That(bool)"/>.
+ /// </summary>
+ /// <param name="condition">The evaluated condition</param>
+ public void Expect(bool condition)
+ {
+ Assert.That(condition, Is.True, null, null);
+ }
+
+ #endregion
+
+ #region ActualValueDelegate
+ /// <summary>
+ /// Apply a constraint to an actual value, succeeding if the constraint
+ /// is satisfied and throwing an assertion exception on failure.
+ /// </summary>
+ /// <param name="expr">A Constraint expression to be applied</param>
+ /// <param name="del">An ActualValueDelegate returning the value to be tested</param>
+ public void Expect<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr)
+ {
+ Assert.That(del, expr.Resolve(), null, null);
+ }
+
+ /// <summary>
+ /// Apply a constraint to an actual value, succeeding if the constraint
+ /// is satisfied and throwing an assertion exception on failure.
+ /// </summary>
+ /// <param name="del">An ActualValueDelegate returning the value to be tested</param>
+ /// <param name="expr">A Constraint expression to be applied</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ public void Expect<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, string message, params object[] args)
+ {
+ Assert.That(del, expr, message, args);
+ }
+ #endregion
+
+ #region TestDelegate
+
+ /// <summary>
+ /// Asserts that the code represented by a delegate throws an exception
+ /// that satisfies the constraint provided.
+ /// </summary>
+ /// <param name="code">A TestDelegate to be executed</param>
+ /// <param name="constraint">A ThrowsConstraint used in the test</param>
+ public void Expect(TestDelegate code, IResolveConstraint constraint)
+ {
+ Assert.That((object)code, constraint);
+ }
+
+ #endregion
+
+ #endregion
+
+ #region Expect<TActual>
+
+ /// <summary>
+ /// Apply a constraint to an actual value, succeeding if the constraint
+ /// is satisfied and throwing an assertion exception on failure.
+ /// </summary>
+ /// <param name="expression">A Constraint to be applied</param>
+ /// <param name="actual">The actual value to test</param>
+ static public void Expect<TActual>(TActual actual, IResolveConstraint expression)
+ {
+ Assert.That(actual, expression, null, null);
+ }
+
+ /// <summary>
+ /// Apply a constraint to an actual value, succeeding if the constraint
+ /// is satisfied and throwing an assertion exception on failure.
+ /// </summary>
+ /// <param name="expression">A Constraint expression to be applied</param>
+ /// <param name="actual">The actual value to test</param>
+ /// <param name="message">The message that will be displayed on failure</param>
+ /// <param name="args">Arguments to be used in formatting the message</param>
+ static public void Expect<TActual>(TActual actual, IResolveConstraint expression, string message, params object[] args)
+ {
+ Assert.That(actual, expression, message, args);
+ }
+
+ #endregion
+
+ #region Map
+ /// <summary>
+ /// Returns a ListMapper based on a collection.
+ /// </summary>
+ /// <param name="original">The original collection</param>
+ /// <returns></returns>
+ public ListMapper Map( ICollection original )
+ {
+ return new ListMapper( original );
+ }
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !SILVERLIGHT && !PORTABLE && !NETCF
+using System;
+using System.Threading;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Marks a test that must run in a particular threading apartment state, causing it
+ /// to run in a separate thread if necessary.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited = true)]
+ public class ApartmentAttribute : PropertyAttribute
+ {
+ /// <summary>
+ /// Construct an ApartmentAttribute
+ /// </summary>
+ /// <param name="apartmentState">The apartment state that this test must be run under. You must pass in a valid apartment state.</param>
+ public ApartmentAttribute(ApartmentState apartmentState)
+ {
+ Guard.ArgumentValid(apartmentState != ApartmentState.Unknown, "must be STA or MTA", "apartmentState");
+ Properties.Add(PropertyNames.ApartmentState, apartmentState);
+ }
+ }
+}
+#endif
--- /dev/null
+// **********************************************************************************
+// The MIT License (MIT)
+//
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy of
+// this software and associated documentation files (the "Software"), to deal in
+// the Software without restriction, including without limitation the rights to
+// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+// the Software, and to permit persons to whom the Software is furnished to do so,
+// subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all
+// copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+// **********************************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+
+#region Using Directives
+
+using System;
+using NUnit.Framework.Internal;
+
+#endregion
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Provides the Author of a test or test fixture.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited=false)]
+ public class AuthorAttribute : PropertyAttribute
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorAttribute"/> class.
+ /// </summary>
+ /// <param name="name">The name of the author.</param>
+ public AuthorAttribute(string name)
+ : base(PropertyNames.Author, name)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorAttribute"/> class.
+ /// </summary>
+ /// <param name="name">The name of the author.</param>
+ /// <param name="email">The email address of the author.</param>
+ public AuthorAttribute(string name, string email)
+ : base(PropertyNames.Author, string.Format("{0} <{1}>", name, email))
+ {
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Attribute used to apply a category to a test
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Assembly, AllowMultiple=true, Inherited=true)]
+ public class CategoryAttribute : NUnitAttribute, IApplyToTest
+ {
+ /// <summary>
+ /// The name of the category
+ /// </summary>
+ protected string categoryName;
+
+ /// <summary>
+ /// Construct attribute for a given category based on
+ /// a name. The name may not contain the characters ',',
+ /// '+', '-' or '!'. However, this is not checked in the
+ /// constructor since it would cause an error to arise at
+ /// as the test was loaded without giving a clear indication
+ /// of where the problem is located. The error is handled
+ /// in NUnitFramework.cs by marking the test as not
+ /// runnable.
+ /// </summary>
+ /// <param name="name">The name of the category</param>
+ public CategoryAttribute(string name)
+ {
+ this.categoryName = name.Trim();
+ }
+
+ /// <summary>
+ /// Protected constructor uses the Type name as the name
+ /// of the category.
+ /// </summary>
+ protected CategoryAttribute()
+ {
+ this.categoryName = this.GetType().Name;
+ if ( categoryName.EndsWith( "Attribute" ) )
+ categoryName = categoryName.Substring( 0, categoryName.Length - 9 );
+ }
+
+ /// <summary>
+ /// The name of the category
+ /// </summary>
+ public string Name
+ {
+ get { return categoryName; }
+ }
+
+ #region IApplyToTest Members
+
+ /// <summary>
+ /// Modifies a test by adding a category to it.
+ /// </summary>
+ /// <param name="test">The test to modify</param>
+ public void ApplyToTest(Test test)
+ {
+ test.Properties.Add(PropertyNames.Category, this.Name);
+
+ if (this.Name.IndexOfAny(new char[] { ',', '!', '+', '-' }) >= 0)
+ {
+ test.RunState = RunState.NotRunnable;
+ test.Properties.Set(PropertyNames.SkipReason, "Category name must not contain ',', '!', '+' or '-'");
+ }
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal.Builders;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Marks a test to use a combinatorial join of any argument
+ /// data provided. Since this is the default, the attribute is
+ /// optional.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
+ public class CombinatorialAttribute : CombiningStrategyAttribute
+ {
+ /// <summary>
+ /// Default constructor
+ /// </summary>
+ public CombinatorialAttribute() : base(new CombinatorialStrategy(), new ParameterDataSourceProvider()) { }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+#if NETCF
+using System.Linq;
+#endif
+
+namespace NUnit.Framework
+{
+ using Interfaces;
+ using Internal;
+ using Internal.Builders;
+
+ /// <summary>
+ /// Marks a test to use a particular CombiningStrategy to join
+ /// any parameter data provided. Since this is the default, the
+ /// attribute is optional.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
+ public abstract class CombiningStrategyAttribute : NUnitAttribute, ITestBuilder, IApplyToTest
+ {
+ private NUnitTestCaseBuilder _builder = new NUnitTestCaseBuilder();
+
+ private ICombiningStrategy _strategy;
+ private IParameterDataProvider _dataProvider;
+
+ /// <summary>
+ /// Construct a CombiningStrategyAttribute incorporating an
+ /// ICombiningStrategy and an IParamterDataProvider.
+ /// </summary>
+ /// <param name="strategy">Combining strategy to be used in combining data</param>
+ /// <param name="provider">An IParameterDataProvider to supply data</param>
+ protected CombiningStrategyAttribute(ICombiningStrategy strategy, IParameterDataProvider provider)
+ {
+ _strategy = strategy;
+ _dataProvider = provider;
+ }
+
+ /// <summary>
+ /// Construct a CombiningStrategyAttribute incorporating an object
+ /// that implements ICombiningStrategy and an IParameterDataProvider.
+ /// This constructor is provided for CLS compliance.
+ /// </summary>
+ /// <param name="strategy">Combining strategy to be used in combining data</param>
+ /// <param name="provider">An IParameterDataProvider to supply data</param>
+ protected CombiningStrategyAttribute(object strategy, object provider)
+ : this((ICombiningStrategy)strategy, (IParameterDataProvider)provider)
+ {
+ }
+
+ #region ITestBuilder Members
+
+ /// <summary>
+ /// Construct one or more TestMethods from a given MethodInfo,
+ /// using available parameter data.
+ /// </summary>
+ /// <param name="method">The MethodInfo for which tests are to be constructed.</param>
+ /// <param name="suite">The suite to which the tests will be added.</param>
+ /// <returns>One or more TestMethods</returns>
+ public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite)
+ {
+ List<TestMethod> tests = new List<TestMethod>();
+
+#if NETCF
+ if (method.ContainsGenericParameters)
+ {
+ var genericParams = method.GetGenericArguments();
+ var numGenericParams = genericParams.Length;
+
+ var o = new object();
+ var tryArgs = Enumerable.Repeat(o, numGenericParams).ToArray();
+ IMethodInfo mi;
+
+ try
+ {
+ // This fails if the generic method has constraints
+ // that are not met by object.
+ mi = method.MakeGenericMethodEx(tryArgs);
+ if (mi == null)
+ return tests;
+ }
+ catch
+ {
+ return tests;
+ }
+
+ var par = mi.GetParameters();
+
+ if (par.Length == 0)
+ return tests;
+
+ var sourceData = par.Select(p => _dataProvider.GetDataFor(p)).ToArray();
+ foreach (var parms in _strategy.GetTestCases(sourceData))
+ {
+ mi = method.MakeGenericMethodEx(parms.Arguments);
+ if (mi == null)
+ {
+ var tm = new TestMethod(method, suite);
+ tm.RunState = RunState.NotRunnable;
+ tm.Properties.Set(PropertyNames.SkipReason, "Incompatible arguments");
+ tests.Add(tm);
+ }
+ else
+ tests.Add(_builder.BuildTestMethod(mi, suite, (TestCaseParameters)parms));
+ }
+
+ return tests;
+ }
+#endif
+ IParameterInfo[] parameters = method.GetParameters();
+
+ if (parameters.Length > 0)
+ {
+ IEnumerable[] sources = new IEnumerable[parameters.Length];
+
+ try
+ {
+ for (int i = 0; i < parameters.Length; i++)
+ sources[i] = _dataProvider.GetDataFor(parameters[i]);
+ }
+ catch (InvalidDataSourceException ex)
+ {
+ var parms = new TestCaseParameters();
+ parms.RunState = RunState.NotRunnable;
+ parms.Properties.Set(PropertyNames.SkipReason, ex.Message);
+ tests.Add(_builder.BuildTestMethod(method, suite, parms));
+ return tests;
+ }
+
+ foreach (var parms in _strategy.GetTestCases(sources))
+ tests.Add(_builder.BuildTestMethod(method, suite, (TestCaseParameters)parms));
+ }
+
+ return tests;
+ }
+
+ #endregion
+
+ #region IApplyToTest Members
+
+ /// <summary>
+ /// Modify the test by adding the name of the combining strategy
+ /// to the properties.
+ /// </summary>
+ /// <param name="test">The test to modify</param>
+ public void ApplyToTest(Test test)
+ {
+ var joinType = _strategy.GetType().Name;
+ if (joinType.EndsWith("Strategy"))
+ joinType = joinType.Substring(0, joinType.Length - 8);
+
+ test.Properties.Set(PropertyNames.JoinType, joinType);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Globalization;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// CultureAttribute is used to mark a test fixture or an
+ /// individual method as applying to a particular Culture only.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Assembly, AllowMultiple = false, Inherited=false)]
+ public class CultureAttribute : IncludeExcludeAttribute, IApplyToTest
+ {
+ private CultureDetector cultureDetector = new CultureDetector();
+ private CultureInfo currentCulture = CultureInfo.CurrentCulture;
+
+ /// <summary>
+ /// Constructor with no cultures specified, for use
+ /// with named property syntax.
+ /// </summary>
+ public CultureAttribute() { }
+
+ /// <summary>
+ /// Constructor taking one or more cultures
+ /// </summary>
+ /// <param name="cultures">Comma-deliminted list of cultures</param>
+ public CultureAttribute(string cultures) : base(cultures) { }
+
+ #region IApplyToTest members
+
+ /// <summary>
+ /// Causes a test to be skipped if this CultureAttribute is not satisfied.
+ /// </summary>
+ /// <param name="test">The test to modify</param>
+ public void ApplyToTest(Test test)
+ {
+ if (test.RunState != RunState.NotRunnable && !IsCultureSupported())
+ {
+ test.RunState = RunState.Skipped;
+ test.Properties.Set(PropertyNames.SkipReason, Reason);
+ }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Tests to determine if the current culture is supported
+ /// based on the properties of this attribute.
+ /// </summary>
+ /// <returns>True, if the current culture is supported</returns>
+ private bool IsCultureSupported()
+ {
+ if (Include != null && !cultureDetector.IsCultureSupported(Include))
+ {
+ Reason = string.Format("Only supported under culture {0}", Include);
+ return false;
+ }
+
+ if (Exclude != null && cultureDetector.IsCultureSupported(Exclude))
+ {
+ Reason = string.Format("Not supported under culture {0}", Exclude);
+ return false;
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Test to determine if the a particular culture or comma-
+ /// delimited set of cultures is in use.
+ /// </summary>
+ /// <param name="culture">Name of the culture or comma-separated list of culture ids</param>
+ /// <returns>True if the culture is in use on the system</returns>
+ public bool IsCultureSupported(string culture)
+ {
+ culture = culture.Trim();
+
+ if (culture.IndexOf(',') >= 0)
+ {
+ if (IsCultureSupported(culture.Split(new char[] { ',' })))
+ return true;
+ }
+ else
+ {
+ if (currentCulture.Name == culture || currentCulture.TwoLetterISOLanguageName == culture)
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Test to determine if one of a collection of cultures
+ /// is being used currently.
+ /// </summary>
+ /// <param name="cultures"></param>
+ /// <returns></returns>
+ public bool IsCultureSupported(string[] cultures)
+ {
+ foreach (string culture in cultures)
+ if (IsCultureSupported(culture))
+ return true;
+
+ return false;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// The abstract base class for all data-providing attributes
+ /// defined by NUnit. Used to select all data sources for a
+ /// method, class or parameter.
+ /// </summary>
+ public abstract class DataAttribute : NUnitAttribute
+ {
+ /// <summary>
+ /// Default constructor
+ /// </summary>
+ public DataAttribute() { }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Used to mark a field for use as a datapoint when executing a theory
+ /// within the same fixture that requires an argument of the field's Type.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
+ public class DatapointAttribute : NUnitAttribute
+ {
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Used to mark a field, property or method providing a set of datapoints to
+ /// be used in executing any theories within the same fixture that require an
+ /// argument of the Type provided. The data source may provide an array of
+ /// the required Type or an <see cref="IEnumerable{T}"/>.
+ /// Synonymous with DatapointsAttribute.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
+ public class DatapointSourceAttribute : NUnitAttribute
+ {
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Used to mark a field, property or method providing a set of datapoints to
+ /// be used in executing any theories within the same fixture that require an
+ /// argument of the Type provided. The data source may provide an array of
+ /// the required Type or an <see cref="IEnumerable{T}"/>.
+ /// Synonymous with DatapointSourceAttribute.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
+ public class DatapointsAttribute : DatapointSourceAttribute
+ {
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Attribute used to provide descriptive text about a
+ /// test case or fixture.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited=false)]
+ public sealed class DescriptionAttribute : PropertyAttribute
+ {
+ /// <summary>
+ /// Construct a description Attribute
+ /// </summary>
+ /// <param name="description">The text of the description</param>
+ public DescriptionAttribute(string description) : base(PropertyNames.Description, description) { }
+ }
+
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// ExplicitAttribute marks a test or test fixture so that it will
+ /// only be run if explicitly executed from the gui or command line
+ /// or if it is included by use of a filter. The test will not be
+ /// run simply because an enclosing suite is run.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)]
+ public class ExplicitAttribute : NUnitAttribute, IApplyToTest
+ {
+ private string _reason;
+
+ /// <summary>
+ /// Default constructor
+ /// </summary>
+ public ExplicitAttribute()
+ {
+ }
+
+ /// <summary>
+ /// Constructor with a reason
+ /// </summary>
+ /// <param name="reason">The reason test is marked explicit</param>
+ public ExplicitAttribute(string reason)
+ {
+ _reason = reason;
+ }
+
+ #region IApplyToTest members
+
+ /// <summary>
+ /// Modifies a test by marking it as explicit.
+ /// </summary>
+ /// <param name="test">The test to modify</param>
+ public void ApplyToTest(Test test)
+ {
+ if (test.RunState != RunState.NotRunnable && test.RunState != RunState.Ignored)
+ {
+ test.RunState = RunState.Explicit;
+ if (_reason != null)
+ test.Properties.Set(PropertyNames.SkipReason, _reason);
+ }
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Globalization;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Attribute used to mark a test that is to be ignored.
+ /// Ignored tests result in a warning message when the
+ /// tests are run.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method|AttributeTargets.Class|AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)]
+ public class IgnoreAttribute : NUnitAttribute, IApplyToTest
+ {
+ private string _reason;
+ private DateTime? _untilDate;
+ private string _until;
+
+ /// <summary>
+ /// Constructs the attribute giving a reason for ignoring the test
+ /// </summary>
+ /// <param name="reason">The reason for ignoring the test</param>
+ public IgnoreAttribute(string reason)
+ {
+ _reason = reason;
+ }
+
+ /// <summary>
+ /// The date in the future to stop ignoring the test as a string in UTC time.
+ /// For example for a date and time, "2014-12-25 08:10:00Z" or for just a date,
+ /// "2014-12-25". If just a date is given, the Ignore will expire at midnight UTC.
+ /// </summary>
+ /// <remarks>
+ /// Once the ignore until date has passed, the test will be marked
+ /// as runnable. Tests with an ignore until date will have an IgnoreUntilDate
+ /// property set which will appear in the test results.
+ /// </remarks>
+ /// <exception cref="FormatException">The string does not contain a valid string representation of a date and time.</exception>
+ public string Until
+ {
+ get { return _until; }
+ set
+ {
+ _until = value;
+ _untilDate = DateTime.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
+ }
+ }
+
+ #region IApplyToTest members
+
+ /// <summary>
+ /// Modifies a test by marking it as Ignored.
+ /// </summary>
+ /// <param name="test">The test to modify</param>
+ public void ApplyToTest(Test test)
+ {
+ if (test.RunState != RunState.NotRunnable)
+ {
+ if (_untilDate.HasValue)
+ {
+ if (_untilDate.Value > DateTime.Now)
+ {
+ test.RunState = RunState.Ignored;
+ string reason = string.Format("Ignoring until {0}. {1}", _untilDate.Value.ToString("u"), _reason);
+ test.Properties.Set(PropertyNames.SkipReason, reason);
+ }
+ test.Properties.Set(PropertyNames.IgnoreUntilDate, _untilDate.Value.ToString("u") );
+
+ return;
+ }
+ test.RunState = RunState.Ignored;
+ test.Properties.Set(PropertyNames.SkipReason, _reason);
+ }
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Abstract base for Attributes that are used to include tests
+ /// in the test run based on environmental settings.
+ /// </summary>
+ public abstract class IncludeExcludeAttribute : NUnitAttribute
+ {
+ private string include;
+ private string exclude;
+ private string reason;
+
+ /// <summary>
+ /// Constructor with no included items specified, for use
+ /// with named property syntax.
+ /// </summary>
+ public IncludeExcludeAttribute() { }
+
+ /// <summary>
+ /// Constructor taking one or more included items
+ /// </summary>
+ /// <param name="include">Comma-delimited list of included items</param>
+ public IncludeExcludeAttribute( string include )
+ {
+ this.include = include;
+ }
+
+ /// <summary>
+ /// Name of the item that is needed in order for
+ /// a test to run. Multiple items may be given,
+ /// separated by a comma.
+ /// </summary>
+ public string Include
+ {
+ get { return this.include; }
+ set { include = value; }
+ }
+
+ /// <summary>
+ /// Name of the item to be excluded. Multiple items
+ /// may be given, separated by a comma.
+ /// </summary>
+ public string Exclude
+ {
+ get { return this.exclude; }
+ set { this.exclude = value; }
+ }
+
+ /// <summary>
+ /// The reason for including or excluding the test
+ /// </summary>
+ public string Reason
+ {
+ get { return reason; }
+ set { reason = value; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// LevelOfParallelismAttribute is used to set the number of worker threads
+ /// that may be allocated by the framework for running tests.
+ /// </summary>
+ [AttributeUsage( AttributeTargets.Assembly, AllowMultiple=false, Inherited=false )]
+ public sealed class LevelOfParallelismAttribute : PropertyAttribute
+ {
+ /// <summary>
+ /// Construct a LevelOfParallelismAttribute.
+ /// </summary>
+ /// <param name="level">The number of worker threads to be created by the framework.</param>
+ public LevelOfParallelismAttribute( int level ) : base( level ) { }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using NUnit.Framework.Internal.Commands;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Summary description for MaxTimeAttribute.
+ /// </summary>
+ [AttributeUsage( AttributeTargets.Method, AllowMultiple=false, Inherited=false )]
+ public sealed class MaxTimeAttribute : PropertyAttribute, IWrapSetUpTearDown
+ {
+ private int _milliseconds;
+ /// <summary>
+ /// Construct a MaxTimeAttribute, given a time in milliseconds.
+ /// </summary>
+ /// <param name="milliseconds">The maximum elapsed time in milliseconds</param>
+ public MaxTimeAttribute( int milliseconds )
+ : base( milliseconds )
+ {
+ _milliseconds = milliseconds;
+ }
+
+ #region ICommandWrapper Members
+
+ TestCommand ICommandWrapper.Wrap(TestCommand command)
+ {
+ return new MaxTimeCommand(command, _milliseconds);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// The abstract base class for all custom attributes defined by NUnit.
+ /// </summary>
+ public abstract class NUnitAttribute : Attribute
+ {
+ /// <summary>
+ /// Default constructor
+ /// </summary>
+ public NUnitAttribute() { }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework
+{
+ using System;
+
+ /// <summary>
+ /// Attribute used to identify a method that is called once
+ /// to perform setup before any child tests are run.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)]
+ public class OneTimeSetUpAttribute : NUnitAttribute
+ {
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework
+{
+ using System;
+
+ /// <summary>
+ /// Attribute used to identify a method that is called once
+ /// after all the child tests have run. The method is
+ /// guaranteed to be called, even if an exception is thrown.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)]
+ public class OneTimeTearDownAttribute : NUnitAttribute
+ {
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2016 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Defines the order that the test will run in
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
+ public class OrderAttribute : NUnitAttribute, IApplyToTest
+ {
+ /// <summary>
+ /// Defines the order that the test will run in
+ /// </summary>
+ public readonly int Order;
+
+ /// <summary>
+ /// Defines the order that the test will run in
+ /// </summary>
+ /// <param name="order"></param>
+ public OrderAttribute(int order)
+ {
+ Order = order;
+ }
+
+ /// <summary>
+ /// Modifies a test as defined for the specific attribute.
+ /// </summary>
+ /// <param name="test">The test to modify</param>
+ public void ApplyToTest(Test test)
+ {
+ if (!test.Properties.ContainsKey(PropertyNames.Order))
+ test.Properties.Set(PropertyNames.Order, Order);
+ }
+ }
+ }
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal.Builders;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Marks a test to use a pairwise join of any argument
+ /// data provided. Arguments will be combined in such a
+ /// way that all possible pairs of arguments are used.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited=false)]
+ public class PairwiseAttribute : CombiningStrategyAttribute
+ {
+ /// <summary>
+ /// Default constructor
+ /// </summary>
+ public PairwiseAttribute() : base(new PairwiseStrategy(), new ParameterDataSourceProvider()) { }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// The ParallelScope enumeration permits specifying the degree to
+ /// which a test and its descendants may be run in parallel.
+ /// </summary>
+ [Flags]
+ public enum ParallelScope
+ {
+ /// <summary>
+ /// No Parallelism is permitted
+ /// </summary>
+ None = 0,
+ /// <summary>
+ /// The test itself may be run in parallel with others at the same level
+ /// </summary>
+ Self = 1,
+ /// <summary>
+ /// Descendants of the test may be run in parallel with one another
+ /// </summary>
+ Children = 2,
+ /// <summary>
+ /// Descendants of the test down to the level of TestFixtures may be run in parallel
+ /// </summary>
+ Fixtures = 4
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// ParallelizableAttribute is used to mark tests that may be run in parallel.
+ /// </summary>
+ [AttributeUsage( AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple=false, Inherited=false )]
+ public sealed class ParallelizableAttribute : PropertyAttribute, IApplyToContext
+ {
+ private ParallelScope _scope;
+
+ /// <summary>
+ /// Construct a ParallelizableAttribute using default ParallelScope.Self.
+ /// </summary>
+ public ParallelizableAttribute() : this(ParallelScope.Self) { }
+
+ /// <summary>
+ /// Construct a ParallelizableAttribute with a specified scope.
+ /// </summary>
+ /// <param name="scope">The ParallelScope associated with this attribute.</param>
+ public ParallelizableAttribute(ParallelScope scope) : base()
+ {
+ _scope = scope;
+
+ Properties.Add(PropertyNames.ParallelScope, scope);
+ }
+
+ #region IApplyToContext Interface
+
+ /// <summary>
+ /// Modify the context to be used for child tests
+ /// </summary>
+ /// <param name="context">The current TestExecutionContext</param>
+ public void ApplyToContext(TestExecutionContext context)
+ {
+ // Don't reflect Self in the context, since it will be
+ // used for descendant tests.
+ context.ParallelScope = _scope & ~ParallelScope.Self;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !PORTABLE
+using System;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// PlatformAttribute is used to mark a test fixture or an
+ /// individual method as applying to a particular platform only.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Assembly, AllowMultiple = true, Inherited=false)]
+ public class PlatformAttribute : IncludeExcludeAttribute, IApplyToTest
+ {
+ private PlatformHelper platformHelper = new PlatformHelper();
+
+ /// <summary>
+ /// Constructor with no platforms specified, for use
+ /// with named property syntax.
+ /// </summary>
+ public PlatformAttribute() { }
+
+ /// <summary>
+ /// Constructor taking one or more platforms
+ /// </summary>
+ /// <param name="platforms">Comma-delimited list of platforms</param>
+ public PlatformAttribute(string platforms) : base(platforms) { }
+
+#region IApplyToTest members
+
+ /// <summary>
+ /// Causes a test to be skipped if this PlatformAttribute is not satisfied.
+ /// </summary>
+ /// <param name="test">The test to modify</param>
+ public void ApplyToTest(Test test)
+ {
+ if (test.RunState != RunState.NotRunnable &&
+ test.RunState != RunState.Ignored &&
+ !platformHelper.IsPlatformSupported(this))
+ {
+ test.RunState = RunState.Skipped;
+ test.Properties.Add(PropertyNames.SkipReason, platformHelper.Reason);
+ }
+ }
+
+#endregion
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Attribute used to provide descriptive text about a
+ /// test case or fixture.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
+ public sealed class PostconditionAttribute : PropertyAttribute
+ {
+ public int Index
+ {
+ set;
+ get;
+ }
+ public string Description
+ {
+ set;
+ get;
+ }
+ /// <summary>
+ /// Construct a description Attribute
+ /// </summary>
+ /// <param name="description">The text of the description</param>
+ public PostconditionAttribute(int index, string description) : base("" + index, description) {
+ Index = index;
+ Description = description;
+ }
+ }
+
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Attribute used to provide descriptive text about a
+ /// test case or fixture.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
+ public sealed class PreconditionAttribute : PropertyAttribute
+ {
+ public int Index
+ {
+ set;
+ get;
+ }
+ public string Description
+ {
+ set;
+ get;
+ }
+ /// <summary>
+ /// Construct a description Attribute
+ /// </summary>
+ /// <param name="description">The text of the description</param>
+ public PreconditionAttribute(int index, string description) : base("" + index, description) {
+ Index = index;
+ Description = description;
+ }
+ }
+
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// PropertyAttribute is used to attach information to a test as a name/value pair..
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Assembly, AllowMultiple=true, Inherited=true)]
+ public class PropertyAttribute : NUnitAttribute, IApplyToTest
+ {
+ private PropertyBag properties = new PropertyBag();
+
+ /// <summary>
+ /// Construct a PropertyAttribute with a name and string value
+ /// </summary>
+ /// <param name="propertyName">The name of the property</param>
+ /// <param name="propertyValue">The property value</param>
+ public PropertyAttribute(string propertyName, string propertyValue)
+ {
+ this.properties.Add(propertyName, propertyValue);
+ }
+
+ /// <summary>
+ /// Construct a PropertyAttribute with a name and int value
+ /// </summary>
+ /// <param name="propertyName">The name of the property</param>
+ /// <param name="propertyValue">The property value</param>
+ public PropertyAttribute(string propertyName, int propertyValue)
+ {
+ this.properties.Add(propertyName, propertyValue);
+ }
+
+ /// <summary>
+ /// Construct a PropertyAttribute with a name and double value
+ /// </summary>
+ /// <param name="propertyName">The name of the property</param>
+ /// <param name="propertyValue">The property value</param>
+ public PropertyAttribute(string propertyName, double propertyValue)
+ {
+ this.properties.Add(propertyName, propertyValue);
+ }
+
+ /// <summary>
+ /// Constructor for derived classes that set the
+ /// property dictionary directly.
+ /// </summary>
+ protected PropertyAttribute() { }
+
+ /// <summary>
+ /// Constructor for use by derived classes that use the
+ /// name of the type as the property name. Derived classes
+ /// must ensure that the Type of the property value is
+ /// a standard type supported by the BCL. Any custom
+ /// types will cause a serialization Exception when
+ /// in the client.
+ /// </summary>
+ protected PropertyAttribute( object propertyValue )
+ {
+ string propertyName = this.GetType().Name;
+ if ( propertyName.EndsWith( "Attribute" ) )
+ propertyName = propertyName.Substring( 0, propertyName.Length - 9 );
+ this.properties.Add(propertyName, propertyValue);
+ }
+
+ /// <summary>
+ /// Gets the property dictionary for this attribute
+ /// </summary>
+ public IPropertyBag Properties
+ {
+ get { return properties; }
+ }
+
+ #region IApplyToTest Members
+
+ /// <summary>
+ /// Modifies a test by adding properties to it.
+ /// </summary>
+ /// <param name="test">The test to modify</param>
+ public virtual void ApplyToTest(Test test)
+ {
+ foreach (string key in Properties.Keys)
+ foreach(object value in Properties[key])
+ test.Properties.Add(key, value);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// RandomAttribute is used to supply a set of random _values
+ /// to a single parameter of a parameterized test.
+ /// </summary>
+ public class RandomAttribute : DataAttribute, IParameterDataSource
+ {
+ private RandomDataSource _source;
+ private int _count;
+
+ #region Constructors
+
+ /// <summary>
+ /// Construct a random set of values appropriate for the Type of the
+ /// parameter on which the attribute appears, specifying only the count.
+ /// </summary>
+ /// <param name="count"></param>
+ public RandomAttribute(int count)
+ {
+ _count = count;
+ }
+
+ /// <summary>
+ /// Construct a set of ints within a specified range
+ /// </summary>
+ public RandomAttribute(int min, int max, int count)
+ {
+ _source = new IntDataSource(min, max, count);
+ }
+
+ /// <summary>
+ /// Construct a set of unsigned ints within a specified range
+ /// </summary>
+ //[CLSCompliant(false)]
+ public RandomAttribute(uint min, uint max, int count)
+ {
+ _source = new UIntDataSource(min, max, count);
+ }
+
+ /// <summary>
+ /// Construct a set of longs within a specified range
+ /// </summary>
+ public RandomAttribute(long min, long max, int count)
+ {
+ _source = new LongDataSource(min, max, count);
+ }
+
+ /// <summary>
+ /// Construct a set of unsigned longs within a specified range
+ /// </summary>
+ //[CLSCompliant(false)]
+ public RandomAttribute(ulong min, ulong max, int count)
+ {
+ _source = new ULongDataSource(min, max, count);
+ }
+
+ /// <summary>
+ /// Construct a set of shorts within a specified range
+ /// </summary>
+ public RandomAttribute(short min, short max, int count)
+ {
+ _source = new ShortDataSource(min, max, count);
+ }
+
+ /// <summary>
+ /// Construct a set of unsigned shorts within a specified range
+ /// </summary>
+ //[CLSCompliant(false)]
+ public RandomAttribute(ushort min, ushort max, int count)
+ {
+ _source = new UShortDataSource(min, max, count);
+ }
+
+ /// <summary>
+ /// Construct a set of doubles within a specified range
+ /// </summary>
+ public RandomAttribute(double min, double max, int count)
+ {
+ _source = new DoubleDataSource(min, max, count);
+ }
+
+ /// <summary>
+ /// Construct a set of floats within a specified range
+ /// </summary>
+ public RandomAttribute(float min, float max, int count)
+ {
+ _source = new FloatDataSource(min, max, count);
+ }
+
+ /// <summary>
+ /// Construct a set of bytes within a specified range
+ /// </summary>
+ public RandomAttribute(byte min, byte max, int count)
+ {
+ _source = new ByteDataSource(min, max, count);
+ }
+
+ /// <summary>
+ /// Construct a set of sbytes within a specified range
+ /// </summary>
+ //[CLSCompliant(false)]
+ public RandomAttribute(sbyte min, sbyte max, int count)
+ {
+ _source = new SByteDataSource(min, max, count);
+ }
+
+ #endregion
+
+ #region IParameterDataSource Interface
+
+ /// <summary>
+ /// Get the collection of _values to be used as arguments.
+ /// </summary>
+ public IEnumerable GetData(IParameterInfo parameter)
+ {
+ // Since a separate Randomizer is used for each parameter,
+ // we can't fill in the data in the constructor of the
+ // attribute. Only now, when GetData is called, do we have
+ // sufficient information to create the values in a
+ // repeatable manner.
+
+ Type parmType = parameter.ParameterType;
+
+ if (_source == null)
+ {
+ if (parmType == typeof(int))
+ _source = new IntDataSource(_count);
+ else if (parmType == typeof(uint))
+ _source = new UIntDataSource(_count);
+ else if (parmType == typeof(long))
+ _source = new LongDataSource(_count);
+ else if (parmType == typeof(ulong))
+ _source = new ULongDataSource(_count);
+ else if (parmType == typeof(short))
+ _source = new ShortDataSource(_count);
+ else if (parmType == typeof(ushort))
+ _source = new UShortDataSource(_count);
+ else if (parmType == typeof(double))
+ _source = new DoubleDataSource(_count);
+ else if (parmType == typeof(float))
+ _source = new FloatDataSource(_count);
+ else if (parmType == typeof(byte))
+ _source = new ByteDataSource(_count);
+ else if (parmType == typeof(sbyte))
+ _source = new SByteDataSource(_count);
+ else if (parmType == typeof(decimal))
+ _source = new DecimalDataSource(_count);
+ else if (parmType.GetTypeInfo().IsEnum)
+ _source = new EnumDataSource(_count);
+ else // Default
+ _source = new IntDataSource(_count);
+ }
+ else if (_source.DataType != parmType && WeConvert(_source.DataType, parmType))
+ {
+ _source = new RandomDataConverter(_source);
+ }
+
+ return _source.GetData(parameter);
+
+ //// Copy the random _values into the data array
+ //// and call the base class which may need to
+ //// convert them to another type.
+ //this.data = new object[values.Count];
+ //for (int i = 0; i < values.Count; i++)
+ // this.data[i] = values[i];
+
+ //return base.GetData(parameter);
+ }
+
+ private bool WeConvert(Type sourceType, Type targetType)
+ {
+ if (targetType == typeof(short) || targetType == typeof(ushort) || targetType == typeof(byte) || targetType == typeof(sbyte))
+ return sourceType == typeof(int);
+
+ if (targetType == typeof(decimal))
+ return sourceType == typeof(int) || sourceType == typeof(double);
+
+ return false;
+ }
+
+ #endregion
+
+ #region Nested DataSource Classes
+
+ #region RandomDataSource
+
+ abstract class RandomDataSource : IParameterDataSource
+ {
+ public Type DataType { get; protected set; }
+
+ public abstract IEnumerable GetData(IParameterInfo parameter);
+ }
+
+ abstract class RandomDataSource<T> : RandomDataSource
+ {
+ private T _min;
+ private T _max;
+ private int _count;
+ private bool _inRange;
+
+ protected Randomizer _randomizer;
+
+ protected RandomDataSource(int count)
+ {
+ _count = count;
+ _inRange = false;
+
+ DataType = typeof(T);
+ }
+
+ protected RandomDataSource(T min, T max, int count)
+ {
+ _min = min;
+ _max = max;
+ _count = count;
+ _inRange = true;
+
+ DataType = typeof(T);
+ }
+
+ public override IEnumerable GetData(IParameterInfo parameter)
+ {
+ //Guard.ArgumentValid(parameter.ParameterType == typeof(T), "Parameter type must be " + typeof(T).Name, "parameter");
+
+ _randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo);
+
+ for (int i = 0; i < _count; i++)
+ yield return _inRange
+ ? GetNext(_min, _max)
+ : GetNext();
+ }
+
+ protected abstract T GetNext();
+ protected abstract T GetNext(T min, T max);
+ }
+
+ #endregion
+
+ #region RandomDataConverter
+
+ class RandomDataConverter : RandomDataSource
+ {
+ IParameterDataSource _source;
+
+ public RandomDataConverter(IParameterDataSource source)
+ {
+ _source = source;
+ }
+
+ public override IEnumerable GetData(IParameterInfo parameter)
+ {
+ Type parmType = parameter.ParameterType;
+
+ foreach (object obj in _source.GetData(parameter))
+ {
+ if (obj is int)
+ {
+ int ival = (int)obj; // unbox first
+ if (parmType == typeof(short))
+ yield return (short)ival;
+ else if (parmType == typeof(ushort))
+ yield return (ushort)ival;
+ else if (parmType == typeof(byte))
+ yield return (byte)ival;
+ else if (parmType == typeof(sbyte))
+ yield return (sbyte)ival;
+ else if (parmType == typeof(decimal))
+ yield return (decimal)ival;
+ }
+ else if (obj is double)
+ {
+ double d = (double)obj; // unbox first
+ if (parmType == typeof(decimal))
+ yield return (decimal)d;
+ }
+ }
+ }
+ }
+
+ #endregion
+
+ #region IntDataSource
+
+ class IntDataSource : RandomDataSource<int>
+ {
+ public IntDataSource(int count) : base(count) { }
+
+ public IntDataSource(int min, int max, int count) : base(min, max, count) { }
+
+ protected override int GetNext()
+ {
+ return _randomizer.Next();
+ }
+
+ protected override int GetNext(int min, int max)
+ {
+ return _randomizer.Next(min, max);
+ }
+ }
+
+ #endregion
+
+ #region UIntDataSource
+
+ class UIntDataSource : RandomDataSource<uint>
+ {
+ public UIntDataSource(int count) : base(count) { }
+
+ public UIntDataSource(uint min, uint max, int count) : base(min, max, count) { }
+
+ protected override uint GetNext()
+ {
+ return _randomizer.NextUInt();
+ }
+
+ protected override uint GetNext(uint min, uint max)
+ {
+ return _randomizer.NextUInt(min, max);
+ }
+ }
+
+ #endregion
+
+ #region LongDataSource
+
+ class LongDataSource : RandomDataSource<long>
+ {
+ public LongDataSource(int count) : base(count) { }
+
+ public LongDataSource(long min, long max, int count) : base(min, max, count) { }
+
+ protected override long GetNext()
+ {
+ return _randomizer.NextLong();
+ }
+
+ protected override long GetNext(long min, long max)
+ {
+ return _randomizer.NextLong(min, max);
+ }
+ }
+
+ #endregion
+
+ #region ULongDataSource
+
+ class ULongDataSource : RandomDataSource<ulong>
+ {
+ public ULongDataSource(int count) : base(count) { }
+
+ public ULongDataSource(ulong min, ulong max, int count) : base(min, max, count) { }
+
+ protected override ulong GetNext()
+ {
+ return _randomizer.NextULong();
+ }
+
+ protected override ulong GetNext(ulong min, ulong max)
+ {
+ return _randomizer.NextULong(min, max);
+ }
+ }
+
+ #endregion
+
+ #region ShortDataSource
+
+ class ShortDataSource : RandomDataSource<short>
+ {
+ public ShortDataSource(int count) : base(count) { }
+
+ public ShortDataSource(short min, short max, int count) : base(min, max, count) { }
+
+ protected override short GetNext()
+ {
+ return _randomizer.NextShort();
+ }
+
+ protected override short GetNext(short min, short max)
+ {
+ return _randomizer.NextShort(min, max);
+ }
+ }
+
+ #endregion
+
+ #region UShortDataSource
+
+ class UShortDataSource : RandomDataSource<ushort>
+ {
+ public UShortDataSource(int count) : base(count) { }
+
+ public UShortDataSource(ushort min, ushort max, int count) : base(min, max, count) { }
+
+ protected override ushort GetNext()
+ {
+ return _randomizer.NextUShort();
+ }
+
+ protected override ushort GetNext(ushort min, ushort max)
+ {
+ return _randomizer.NextUShort(min, max);
+ }
+ }
+
+ #endregion
+
+ #region DoubleDataSource
+
+ class DoubleDataSource : RandomDataSource<double>
+ {
+ public DoubleDataSource(int count) : base(count) { }
+
+ public DoubleDataSource(double min, double max, int count) : base(min, max, count) { }
+
+ protected override double GetNext()
+ {
+ return _randomizer.NextDouble();
+ }
+
+ protected override double GetNext(double min, double max)
+ {
+ return _randomizer.NextDouble(min, max);
+ }
+ }
+
+ #endregion
+
+ #region FloatDataSource
+
+ class FloatDataSource : RandomDataSource<float>
+ {
+ public FloatDataSource(int count) : base(count) { }
+
+ public FloatDataSource(float min, float max, int count) : base(min, max, count) { }
+
+ protected override float GetNext()
+ {
+ return _randomizer.NextFloat();
+ }
+
+ protected override float GetNext(float min, float max)
+ {
+ return _randomizer.NextFloat(min, max);
+ }
+ }
+
+ #endregion
+
+ #region ByteDataSource
+
+ class ByteDataSource : RandomDataSource<byte>
+ {
+ public ByteDataSource(int count) : base(count) { }
+
+ public ByteDataSource(byte min, byte max, int count) : base(min, max, count) { }
+
+ protected override byte GetNext()
+ {
+ return _randomizer.NextByte();
+ }
+
+ protected override byte GetNext(byte min, byte max)
+ {
+ return _randomizer.NextByte(min, max);
+ }
+ }
+
+ #endregion
+
+ #region SByteDataSource
+
+ class SByteDataSource : RandomDataSource<sbyte>
+ {
+ public SByteDataSource(int count) : base(count) { }
+
+ public SByteDataSource(sbyte min, sbyte max, int count) : base(min, max, count) { }
+
+ protected override sbyte GetNext()
+ {
+ return _randomizer.NextSByte();
+ }
+
+ protected override sbyte GetNext(sbyte min, sbyte max)
+ {
+ return _randomizer.NextSByte(min, max);
+ }
+ }
+
+ #endregion
+
+ #region EnumDataSource
+
+ class EnumDataSource : RandomDataSource
+ {
+ private int _count;
+
+ public EnumDataSource(int count)
+ {
+ _count = count;
+ DataType = typeof(Enum);
+ }
+
+ public override IEnumerable GetData(IParameterInfo parameter)
+ {
+ Guard.ArgumentValid(parameter.ParameterType.GetTypeInfo().IsEnum, "EnumDataSource requires an enum parameter", "parameter");
+
+ Randomizer randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo);
+ DataType = parameter.ParameterType;
+
+ for (int i = 0; i < _count; i++ )
+ yield return randomizer.NextEnum(parameter.ParameterType);
+ }
+ }
+
+ #endregion
+
+ #region DecimalDataSource
+
+ // Currently, Randomizer doesn't implement methods for decimal
+ // so we use random Ulongs and convert them. This doesn't cover
+ // the full range of decimal, so it's temporary.
+ class DecimalDataSource : RandomDataSource<decimal>
+ {
+ public DecimalDataSource(int count) : base(count) { }
+
+ public DecimalDataSource(decimal min, decimal max, int count) : base(min, max, count) { }
+
+ protected override decimal GetNext()
+ {
+ return _randomizer.NextDecimal();
+ }
+
+ protected override decimal GetNext(decimal min, decimal max)
+ {
+ return _randomizer.NextDecimal(min, max);
+ }
+ }
+
+ #endregion
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// RangeAttribute is used to supply a range of _values to an
+ /// individual parameter of a parameterized test.
+ /// </summary>
+ public class RangeAttribute : ValuesAttribute
+ {
+ #region Ints
+
+ /// <summary>
+ /// Construct a range of ints using default step of 1
+ /// </summary>
+ /// <param name="from"></param>
+ /// <param name="to"></param>
+ public RangeAttribute(int from, int to) : this(from, to, from > to ? -1 : 1) { }
+
+ /// <summary>
+ /// Construct a range of ints specifying the step size
+ /// </summary>
+ /// <param name="from"></param>
+ /// <param name="to"></param>
+ /// <param name="step"></param>
+ public RangeAttribute(int from, int to, int step)
+ {
+ Guard.ArgumentValid(step > 0 && to >= from || step < 0 && to <= from,
+ "Step must be positive with to >= from or negative with to <= from", "step");
+
+ int count = (to - from) / step + 1;
+ this.data = new object[count];
+ int index = 0;
+ for (int val = from; index < count; val += step)
+ this.data[index++] = val;
+ }
+
+ #endregion
+
+ #region Unsigned Ints
+
+ /// <summary>
+ /// Construct a range of unsigned ints using default step of 1
+ /// </summary>
+ /// <param name="from"></param>
+ /// <param name="to"></param>
+ //[CLSCompliant(false)]
+ public RangeAttribute(uint from, uint to) : this(from, to, 1u) { }
+
+ /// <summary>
+ /// Construct a range of unsigned ints specifying the step size
+ /// </summary>
+ /// <param name="from"></param>
+ /// <param name="to"></param>
+ /// <param name="step"></param>
+ //[CLSCompliant(false)]
+ public RangeAttribute(uint from, uint to, uint step)
+ {
+ Guard.ArgumentValid(step > 0, "Step must be greater than zero", "step");
+ Guard.ArgumentValid(to >= from, "Value of to must be greater than or equal to from", "to");
+
+ uint count = (to - from) / step + 1;
+ this.data = new object[count];
+ uint index = 0;
+ for (uint val = from; index < count; val += step)
+ this.data[index++] = val;
+ }
+
+ #endregion
+
+ #region Longs
+
+ /// <summary>
+ /// Construct a range of longs using a default step of 1
+ /// </summary>
+ /// <param name="from"></param>
+ /// <param name="to"></param>
+ public RangeAttribute(long from, long to) : this(from, to, from > to ? -1L : 1L) { }
+
+ /// <summary>
+ /// Construct a range of longs
+ /// </summary>
+ /// <param name="from"></param>
+ /// <param name="to"></param>
+ /// <param name="step"></param>
+ public RangeAttribute(long from, long to, long step)
+ {
+ Guard.ArgumentValid(step > 0L && to >= from || step < 0L && to <= from,
+ "Step must be positive with to >= from or negative with to <= from", "step");
+
+ long count = (to - from) / step + 1;
+ this.data = new object[count];
+ int index = 0;
+ for (long val = from; index < count; val += step)
+ this.data[index++] = val;
+ }
+
+ #endregion
+
+ #region Unsigned Longs
+
+ /// <summary>
+ /// Construct a range of unsigned longs using default step of 1
+ /// </summary>
+ /// <param name="from"></param>
+ /// <param name="to"></param>
+ //[CLSCompliant(false)]
+ public RangeAttribute(ulong from, ulong to) : this(from, to, 1ul) { }
+
+ /// <summary>
+ /// Construct a range of unsigned longs specifying the step size
+ /// </summary>
+ /// <param name="from"></param>
+ /// <param name="to"></param>
+ /// <param name="step"></param>
+ //[CLSCompliant(false)]
+ public RangeAttribute(ulong from, ulong to, ulong step)
+ {
+ Guard.ArgumentValid(step > 0, "Step must be greater than zero", "step");
+ Guard.ArgumentValid(to >= from, "Value of to must be greater than or equal to from", "to");
+
+ ulong count = (to - from) / step + 1;
+ this.data = new object[count];
+ ulong index = 0;
+ for (ulong val = from; index < count; val += step)
+ this.data[index++] = val;
+ }
+
+ #endregion
+
+ #region Doubles
+
+ /// <summary>
+ /// Construct a range of doubles
+ /// </summary>
+ /// <param name="from"></param>
+ /// <param name="to"></param>
+ /// <param name="step"></param>
+ public RangeAttribute(double from, double to, double step)
+ {
+ Guard.ArgumentValid(step > 0.0D && to >= from || step < 0.0D && to <= from,
+ "Step must be positive with to >= from or negative with to <= from", "step");
+
+ double aStep = Math.Abs(step);
+ double tol = aStep / 1000;
+ int count = (int)(Math.Abs(to - from) / aStep + tol + 1);
+ this.data = new object[count];
+ int index = 0;
+ for (double val = from; index < count; val += step)
+ this.data[index++] = val;
+ }
+
+ #endregion
+
+ #region Floats
+
+ /// <summary>
+ /// Construct a range of floats
+ /// </summary>
+ /// <param name="from"></param>
+ /// <param name="to"></param>
+ /// <param name="step"></param>
+ public RangeAttribute(float from, float to, float step)
+ {
+ Guard.ArgumentValid(step > 0.0F && to >= from || step < 0.0F && to <= from,
+ "Step must be positive with to >= from or negative with to <= from", "step");
+
+ float aStep = Math.Abs(step);
+ float tol = aStep / 1000;
+ int count = (int)(Math.Abs(to - from) / aStep + tol + 1);
+ this.data = new object[count];
+ int index = 0;
+ for (float val = from; index < count; val += step)
+ this.data[index++] = val;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+
+// TODO: Rework this
+// RepeatAttribute should either
+// 1) Apply at load time to create the exact number of tests, or
+// 2) Apply at run time, generating tests or results dynamically
+//
+// #1 is feasible but doesn't provide much benefit
+// #2 requires infrastructure for dynamic test cases first
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.Internal.Commands;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// RepeatAttribute may be applied to test case in order
+ /// to run it multiple times.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
+ public class RepeatAttribute : PropertyAttribute, IWrapSetUpTearDown
+ {
+ private int _count;
+
+ /// <summary>
+ /// Construct a RepeatAttribute
+ /// </summary>
+ /// <param name="count">The number of times to run the test</param>
+ public RepeatAttribute(int count) : base(count)
+ {
+ _count = count;
+ }
+
+ #region IWrapSetUpTearDown Members
+
+ /// <summary>
+ /// Wrap a command and return the result.
+ /// </summary>
+ /// <param name="command">The command to be wrapped</param>
+ /// <returns>The wrapped command</returns>
+ public TestCommand Wrap(TestCommand command)
+ {
+ return new RepeatedTestCommand(command, _count);
+ }
+
+ #endregion
+
+ #region Nested RepeatedTestCommand Class
+
+ /// <summary>
+ /// The test command for the RepeatAttribute
+ /// </summary>
+ public class RepeatedTestCommand : DelegatingTestCommand
+ {
+ private int repeatCount;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RepeatedTestCommand"/> class.
+ /// </summary>
+ /// <param name="innerCommand">The inner command.</param>
+ /// <param name="repeatCount">The number of repetitions</param>
+ public RepeatedTestCommand(TestCommand innerCommand, int repeatCount)
+ : base(innerCommand)
+ {
+ this.repeatCount = repeatCount;
+ }
+
+ /// <summary>
+ /// Runs the test, saving a TestResult in the supplied TestExecutionContext.
+ /// </summary>
+ /// <param name="context">The context in which the test should run.</param>
+ /// <returns>A TestResult</returns>
+ public override TestResult Execute(TestExecutionContext context)
+ {
+ int count = repeatCount;
+
+ while (count-- > 0)
+ {
+ context.CurrentResult = innerCommand.Execute(context);
+
+ // TODO: We may want to change this so that all iterations are run
+ if (context.CurrentResult.ResultState != ResultState.Success)
+ break;
+ }
+
+ return context.CurrentResult;
+ }
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !SILVERLIGHT && !PORTABLE && !NETCF
+using System;
+using System.Threading;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Marks a test that must run in the MTA, causing it
+ /// to run in a separate thread if necessary.
+ ///
+ /// On methods, you may also use MTAThreadAttribute
+ /// to serve the same purpose.
+ /// </summary>
+ [Obsolete("Use ApartmentAttribute and pass in ApartmentState.MTA instead")]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited=true)]
+ public class RequiresMTAAttribute : PropertyAttribute
+ {
+ /// <summary>
+ /// Construct a RequiresMTAAttribute
+ /// </summary>
+ public RequiresMTAAttribute()
+ {
+ this.Properties.Add(PropertyNames.ApartmentState, ApartmentState.MTA);
+ }
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !SILVERLIGHT && !PORTABLE && !NETCF
+using System;
+using System.Threading;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Marks a test that must run in the STA, causing it
+ /// to run in a separate thread if necessary.
+ /// </summary>
+ [Obsolete( "Use ApartmentAttribute and pass in ApartmentState.STA instead" )]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited=true)]
+ public class RequiresSTAAttribute : PropertyAttribute
+ {
+ /// <summary>
+ /// Construct a RequiresSTAAttribute
+ /// </summary>
+ public RequiresSTAAttribute()
+ {
+ this.Properties.Add(PropertyNames.ApartmentState, ApartmentState.STA);
+ }
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !SILVERLIGHT && !PORTABLE
+using System;
+using System.Threading;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Marks a test that must run on a separate thread.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited=true)]
+ public class RequiresThreadAttribute : PropertyAttribute, IApplyToTest
+ {
+ /// <summary>
+ /// Construct a RequiresThreadAttribute
+ /// </summary>
+ public RequiresThreadAttribute()
+ : base(true) { }
+
+ /// <summary>
+ /// Construct a RequiresThreadAttribute, specifying the apartment
+ /// </summary>
+ public RequiresThreadAttribute(ApartmentState apartment)
+ : base(true)
+ {
+ this.Properties.Add(PropertyNames.ApartmentState, apartment);
+ }
+
+ void IApplyToTest.ApplyToTest(Test test)
+ {
+ test.RequiresThread = true;
+ base.ApplyToTest(test);
+ }
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+
+// TODO: Rework this
+// RepeatAttribute should either
+// 1) Apply at load time to create the exact number of tests, or
+// 2) Apply at run time, generating tests or results dynamically
+//
+// #1 is feasible but doesn't provide much benefit
+// #2 requires infrastructure for dynamic test cases first
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.Internal.Commands;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// RepeatAttribute may be applied to test case in order
+ /// to run it multiple times.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
+ public class RetryAttribute : PropertyAttribute, IWrapSetUpTearDown
+ {
+ private int _count;
+
+ /// <summary>
+ /// Construct a RepeatAttribute
+ /// </summary>
+ /// <param name="count">The number of times to run the test</param>
+ public RetryAttribute(int count) : base(count)
+ {
+ _count = count;
+ }
+
+ #region IWrapSetUpTearDown Members
+
+ /// <summary>
+ /// Wrap a command and return the result.
+ /// </summary>
+ /// <param name="command">The command to be wrapped</param>
+ /// <returns>The wrapped command</returns>
+ public TestCommand Wrap(TestCommand command)
+ {
+ return new RetryCommand(command, _count);
+ }
+
+ #endregion
+
+ #region Nested RetryCommand Class
+
+ /// <summary>
+ /// The test command for the RetryAttribute
+ /// </summary>
+ public class RetryCommand : DelegatingTestCommand
+ {
+ private int _retryCount;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RetryCommand"/> class.
+ /// </summary>
+ /// <param name="innerCommand">The inner command.</param>
+ /// <param name="retryCount">The number of repetitions</param>
+ public RetryCommand(TestCommand innerCommand, int retryCount)
+ : base(innerCommand)
+ {
+ _retryCount = retryCount;
+ }
+
+ /// <summary>
+ /// Runs the test, saving a TestResult in the supplied TestExecutionContext.
+ /// </summary>
+ /// <param name="context">The context in which the test should run.</param>
+ /// <returns>A TestResult</returns>
+ public override TestResult Execute(TestExecutionContext context)
+ {
+ int count = _retryCount;
+
+ while (count-- > 0)
+ {
+ context.CurrentResult = innerCommand.Execute(context);
+
+ if (context.CurrentResult.ResultState != ResultState.Failure)
+ {
+ break;
+ }
+ }
+
+ return context.CurrentResult;
+ }
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal.Builders;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Marks a test to use a Sequential join of any argument
+ /// data provided. Arguments will be combined into test cases,
+ /// taking the next value of each argument until all are used.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited=false)]
+ public class SequentialAttribute : CombiningStrategyAttribute
+ {
+ /// <summary>
+ /// Default constructor
+ /// </summary>
+ public SequentialAttribute() : base(new SequentialStrategy(), new ParameterDataSourceProvider()) { }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !NETCF && !PORTABLE
+using System;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Summary description for SetCultureAttribute.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Assembly, AllowMultiple=false, Inherited=true)]
+ public class SetCultureAttribute : PropertyAttribute, IApplyToContext
+ {
+ private string _culture;
+
+ /// <summary>
+ /// Construct given the name of a culture
+ /// </summary>
+ /// <param name="culture"></param>
+ public SetCultureAttribute( string culture ) : base( PropertyNames.SetCulture, culture )
+ {
+ _culture = culture;
+ }
+
+#region IApplyToContext Members
+
+ void IApplyToContext.ApplyToContext(TestExecutionContext context)
+ {
+ context.CurrentCulture = new System.Globalization.CultureInfo(_culture);
+ }
+
+#endregion
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !NETCF && !PORTABLE
+using System;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Summary description for SetUICultureAttribute.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Assembly, AllowMultiple = false, Inherited=true)]
+ public class SetUICultureAttribute : PropertyAttribute, IApplyToContext
+ {
+ private string _culture;
+
+ /// <summary>
+ /// Construct given the name of a culture
+ /// </summary>
+ /// <param name="culture"></param>
+ public SetUICultureAttribute(string culture) : base("SetUICulture", culture)
+ {
+ _culture = culture;
+ }
+
+#region IApplyToContext Members
+
+ void IApplyToContext.ApplyToContext(TestExecutionContext context)
+ {
+ context.CurrentUICulture = new System.Globalization.CultureInfo(_culture);
+ }
+
+#endregion
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework
+{
+ using System;
+
+ /// <summary>
+ /// Attribute used to mark a class that contains one-time SetUp
+ /// and/or TearDown methods that apply to all the tests in a
+ /// namespace or an assembly.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited=true)]
+ public class SetUpAttribute : NUnitAttribute
+ { }
+
+ /// <summary>
+ /// Attribute used to mark a class that contains one-time SetUp
+ /// and/or TearDown methods that apply to all the tests in a
+ /// namespace or an assembly.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited=true)]
+ public class PreTestAttribute : NUnitAttribute
+ { }
+
+ /// <summary>
+ /// Attribute used to mark a class that contains one-time SetUp
+ /// and/or TearDown methods that apply to all the tests in a
+ /// namespace or an assembly.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited=true)]
+ public class PostTestAttribute : NUnitAttribute
+ { }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+
+namespace NUnit.Framework
+{
+ using Interfaces;
+ using Internal;
+
+ /// <summary>
+ /// SetUpFixtureAttribute is used to identify a SetUpFixture
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
+ public class SetUpFixtureAttribute : NUnitAttribute, IFixtureBuilder
+ {
+ #region ISuiteBuilder Members
+
+ /// <summary>
+ /// Build a SetUpFixture from type provided. Normally called for a Type
+ /// on which the attribute has been placed.
+ /// </summary>
+ /// <param name="typeInfo">The type info of the fixture to be used.</param>
+ /// <returns>A SetUpFixture object as a TestSuite.</returns>
+ public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo)
+ {
+ SetUpFixture fixture = new SetUpFixture(typeInfo);
+
+ if (fixture.RunState != RunState.NotRunnable)
+ {
+ string reason = null;
+ if (!IsValidFixtureType(typeInfo, ref reason))
+ {
+ fixture.RunState = RunState.NotRunnable;
+ fixture.Properties.Set(PropertyNames.SkipReason, reason);
+ }
+ }
+
+ return new TestSuite[] { fixture };
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ private bool IsValidFixtureType(ITypeInfo typeInfo, ref string reason)
+ {
+ if (typeInfo.IsAbstract)
+ {
+ reason = string.Format("{0} is an abstract class", typeInfo.FullName);
+ return false;
+ }
+
+ if (!typeInfo.HasConstructor(new Type[0]))
+ {
+ reason = string.Format("{0} does not have a default constructor", typeInfo.FullName);
+ return false;
+ }
+
+ var invalidAttributes = new Type[] {
+ typeof(SetUpAttribute),
+ typeof(TearDownAttribute),
+#pragma warning disable 618 // Obsolete Attributes
+ typeof(TestFixtureSetUpAttribute),
+ typeof(TestFixtureTearDownAttribute) };
+#pragma warning restore
+
+ foreach (Type invalidType in invalidAttributes)
+ if (typeInfo.HasMethodWithAttribute(invalidType))
+ {
+ reason = invalidType.Name + " attribute not allowed in a SetUpFixture";
+ return false;
+ }
+
+ return true;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2016 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// SingleThreadedAttribute applies to a test fixture and indicates
+ /// that all the child tests must be run on the same thread as the
+ /// OneTimeSetUp and OneTimeTearDown. It sets a flag in the
+ /// TestExecutionContext and forces all tests to be run sequentially
+ /// on the current thread. Any ParallelScope setting is ignored.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
+ public class SingleThreadedAttribute : NUnitAttribute, IApplyToContext
+ {
+ #region IApplyToContext Members
+
+ /// <summary>
+ /// Apply changes to the TestExecutionContext
+ /// </summary>
+ /// <param name="context">The TestExecutionContext</param>
+ public void ApplyToContext(TestExecutionContext context)
+ {
+ context.IsSingleThreaded = true;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Attribute used to provide descriptive text about a
+ /// test case or fixture.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
+ public sealed class StepAttribute : PropertyAttribute
+ {
+ public int Index {
+ set;
+ get;
+ }
+ public string Description
+ {
+ set;
+ get;
+ }
+ /// <summary>
+ /// Construct a description Attribute
+ /// </summary>
+ /// <param name="description">The text of the description</param>
+ public StepAttribute(int index, string description) : base("" + index, description) {
+ Index = index;
+ Description = description;
+ }
+ }
+
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework
+{
+ using System;
+
+ /// <summary>
+ /// Attribute used to identify a method that is called
+ /// immediately after each test is run. The method is
+ /// guaranteed to be called, even if an exception is thrown.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)]
+ public class TearDownAttribute : NUnitAttribute
+ {}
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace NUnit.Framework
+{
+ using Interfaces;
+
+ /// <summary>
+ /// Provide actions to execute before and after tests.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
+ public abstract class TestActionAttribute : Attribute, ITestAction
+ {
+ /// <summary>
+ /// Executed before each test is run
+ /// </summary>
+ /// <param name="test">The test that is going to be run.</param>
+ public virtual void BeforeTest(ITest test) { }
+
+ /// <summary>
+ /// Executed after each test is run
+ /// </summary>
+ /// <param name="test">The test that has just been run.</param>
+ public virtual void AfterTest(ITest test) { }
+
+ /// <summary>
+ /// Provides the target for the action attribute
+ /// </summary>
+ public virtual ActionTargets Targets
+ {
+ get { return ActionTargets.Default; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2016 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// TestAssemblyDirectoryResolveAttribute is used to mark a test assembly as needing a
+ /// special assembly resolution hook that will explicitly search the test assembly's
+ /// directory for dependent assemblies. This works around a conflict between mixed-mode
+ /// assembly initialization and tests running in their own AppDomain in some cases.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)]
+ public class TestAssemblyDirectoryResolveAttribute : NUnitAttribute
+ {
+ }
+
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+
+namespace NUnit.Framework
+{
+ using System;
+ using System.Collections.Generic;
+ using NUnit.Framework.Interfaces;
+ using NUnit.Framework.Internal;
+ using NUnit.Framework.Internal.Builders;
+
+ /// <summary>
+ /// Adding this attribute to a method within a <seealso cref="TestFixtureAttribute"/>
+ /// class makes the method callable from the NUnit test runner. There is a property
+ /// called Description which is optional which you can provide a more detailed test
+ /// description. This class cannot be inherited.
+ /// </summary>
+ ///
+ /// <example>
+ /// [TestFixture]
+ /// public class Fixture
+ /// {
+ /// [Test]
+ /// public void MethodToTest()
+ /// {}
+ ///
+ /// [Test(Description = "more detailed description")]
+ /// public void TestDescriptionMethod()
+ /// {}
+ /// }
+ /// </example>
+ ///
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)]
+ public class TestAttribute : NUnitAttribute, ISimpleTestBuilder, IApplyToTest, IImplyFixture
+ {
+ private object _expectedResult;
+ private readonly NUnitTestCaseBuilder _builder = new NUnitTestCaseBuilder();
+
+ /// <summary>
+ /// Descriptive text for this test
+ /// </summary>
+ public string Description { get; set; }
+
+ /// <summary>
+ /// The author of this test
+ /// </summary>
+ public string Author { get; set; }
+
+ /// <summary>
+ /// The type that this test is testing
+ /// </summary>
+ public Type TestOf { get; set; }
+
+ #region IApplyToTest Members
+
+ /// <summary>
+ /// Modifies a test by adding a description, if not already set.
+ /// </summary>
+ /// <param name="test">The test to modify</param>
+ public void ApplyToTest(Test test)
+ {
+ if (!test.Properties.ContainsKey(PropertyNames.Description) && Description != null)
+ test.Properties.Set(PropertyNames.Description, Description);
+
+ if (!test.Properties.ContainsKey(PropertyNames.Author) && Author != null)
+ test.Properties.Set(PropertyNames.Author, Author);
+
+ if (!test.Properties.ContainsKey(PropertyNames.TestOf) && TestOf != null)
+ test.Properties.Set(PropertyNames.TestOf, TestOf.FullName);
+
+ }
+
+ #endregion
+
+ #region ITestExpectedResult Members
+
+ /// <summary>
+ /// Gets or sets the expected result.
+ /// </summary>
+ /// <value>The result.</value>
+ public object ExpectedResult
+ {
+ get { return _expectedResult; }
+ set
+ {
+ _expectedResult = value;
+ HasExpectedResult = true;
+ }
+ }
+
+ /// <summary>
+ /// Returns true if an expected result has been set
+ /// </summary>
+ public bool HasExpectedResult { get; private set; }
+
+ #endregion
+
+ #region ISimpleTestBuilder Members
+
+ /// <summary>
+ /// Construct a TestMethod from a given method.
+ /// </summary>
+ /// <param name="method">The method for which a test is to be constructed.</param>
+ /// <param name="suite">The suite to which the test will be added.</param>
+ /// <returns>A TestMethod</returns>
+ public TestMethod BuildFrom(IMethodInfo method, Test suite)
+ {
+ TestCaseParameters parms = null;
+
+ if (this.HasExpectedResult)
+ {
+ parms = new TestCaseParameters();
+ parms.ExpectedResult = this.ExpectedResult;
+ }
+
+ return _builder.BuildTestMethod(method, suite, parms);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.Internal.Builders;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// TestCaseAttribute is used to mark parameterized test cases
+ /// and provide them with their arguments.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited=false)]
+ public class TestCaseAttribute : NUnitAttribute, ITestBuilder, ITestCaseData, IImplyFixture
+ {
+ #region Constructors
+
+ /// <summary>
+ /// Construct a TestCaseAttribute with a list of arguments.
+ /// This constructor is not CLS-Compliant
+ /// </summary>
+ /// <param name="arguments"></param>
+ public TestCaseAttribute(params object[] arguments)
+ {
+ RunState = RunState.Runnable;
+
+ if (arguments == null)
+ Arguments = new object[] { null };
+ else
+ Arguments = arguments;
+
+ Properties = new PropertyBag();
+ }
+
+ /// <summary>
+ /// Construct a TestCaseAttribute with a single argument
+ /// </summary>
+ /// <param name="arg"></param>
+ public TestCaseAttribute(object arg)
+ {
+ RunState = RunState.Runnable;
+ Arguments = new object[] { arg };
+ Properties = new PropertyBag();
+ }
+
+ /// <summary>
+ /// Construct a TestCaseAttribute with a two arguments
+ /// </summary>
+ /// <param name="arg1"></param>
+ /// <param name="arg2"></param>
+ public TestCaseAttribute(object arg1, object arg2)
+ {
+ RunState = RunState.Runnable;
+ Arguments = new object[] { arg1, arg2 };
+ Properties = new PropertyBag();
+ }
+
+ /// <summary>
+ /// Construct a TestCaseAttribute with a three arguments
+ /// </summary>
+ /// <param name="arg1"></param>
+ /// <param name="arg2"></param>
+ /// <param name="arg3"></param>
+ public TestCaseAttribute(object arg1, object arg2, object arg3)
+ {
+ RunState = RunState.Runnable;
+ Arguments = new object[] { arg1, arg2, arg3 };
+ Properties = new PropertyBag();
+ }
+
+ #endregion
+
+ #region ITestData Members
+
+ /// <summary>
+ /// Gets or sets the name of the test.
+ /// </summary>
+ /// <value>The name of the test.</value>
+ public string TestName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the RunState of this test case.
+ /// </summary>
+ public RunState RunState { get; private set; }
+
+ /// <summary>
+ /// Gets the list of arguments to a test case
+ /// </summary>
+ public object[] Arguments { get; private set; }
+
+ /// <summary>
+ /// Gets the properties of the test case
+ /// </summary>
+ public IPropertyBag Properties { get; private set; }
+
+ #endregion
+
+ #region ITestCaseData Members
+
+ /// <summary>
+ /// Gets or sets the expected result.
+ /// </summary>
+ /// <value>The result.</value>
+ public object ExpectedResult
+ {
+ get { return _expectedResult; }
+ set
+ {
+ _expectedResult = value;
+ HasExpectedResult = true;
+ }
+ }
+ private object _expectedResult;
+
+ /// <summary>
+ /// Returns true if the expected result has been set
+ /// </summary>
+ public bool HasExpectedResult { get; private set; }
+
+ #endregion
+
+ #region Other Properties
+
+ /// <summary>
+ /// Gets or sets the description.
+ /// </summary>
+ /// <value>The description.</value>
+ public string Description
+ {
+ get { return Properties.Get(PropertyNames.Description) as string; }
+ set { Properties.Set(PropertyNames.Description, value); }
+ }
+
+ /// <summary>
+ /// The author of this test
+ /// </summary>
+ public string Author
+ {
+ get { return Properties.Get(PropertyNames.Author) as string; }
+ set { Properties.Set(PropertyNames.Author, value); }
+ }
+
+ /// <summary>
+ /// The type that this test is testing
+ /// </summary>
+ public Type TestOf
+ {
+ get { return _testOf; }
+ set
+ {
+ _testOf = value;
+ Properties.Set(PropertyNames.TestOf, value.FullName);
+ }
+ }
+ private Type _testOf;
+
+ /// <summary>
+ /// Gets or sets the reason for ignoring the test
+ /// </summary>
+ public string Ignore
+ {
+ get { return IgnoreReason; }
+ set { IgnoreReason = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestCaseAttribute"/> is explicit.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if explicit; otherwise, <c>false</c>.
+ /// </value>
+ public bool Explicit
+ {
+ get { return RunState == RunState.Explicit; }
+ set { RunState = value ? RunState.Explicit : RunState.Runnable; }
+ }
+
+ /// <summary>
+ /// Gets or sets the reason for not running the test.
+ /// </summary>
+ /// <value>The reason.</value>
+ public string Reason
+ {
+ get { return Properties.Get(PropertyNames.SkipReason) as string; }
+ set { Properties.Set(PropertyNames.SkipReason, value); }
+ }
+
+ /// <summary>
+ /// Gets or sets the ignore reason. When set to a non-null
+ /// non-empty value, the test is marked as ignored.
+ /// </summary>
+ /// <value>The ignore reason.</value>
+ public string IgnoreReason
+ {
+ get { return Reason; }
+ set
+ {
+ RunState = RunState.Ignored;
+ Reason = value;
+ }
+ }
+
+#if !PORTABLE
+ /// <summary>
+ /// Comma-delimited list of platforms to run the test for
+ /// </summary>
+ public string IncludePlatform { get; set; }
+
+ /// <summary>
+ /// Comma-delimited list of platforms to not run the test for
+ /// </summary>
+ public string ExcludePlatform { get; set; }
+#endif
+
+ /// <summary>
+ /// Gets and sets the category for this test case.
+ /// May be a comma-separated list of categories.
+ /// </summary>
+ public string Category
+ {
+ get { return Properties.Get(PropertyNames.Category) as string; }
+ set
+ {
+ foreach (string cat in value.Split(new char[] { ',' }) )
+ Properties.Add(PropertyNames.Category, cat);
+ }
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ private TestCaseParameters GetParametersForTestCase(IMethodInfo method)
+ {
+ TestCaseParameters parms;
+
+ try
+ {
+#if NETCF
+ var tmethod = method.MakeGenericMethodEx(Arguments);
+ if (tmethod == null)
+ throw new NotSupportedException("Cannot determine generic types from probing");
+ method = tmethod;
+#endif
+
+ IParameterInfo[] parameters = method.GetParameters();
+ int argsNeeded = parameters.Length;
+ int argsProvided = Arguments.Length;
+
+ parms = new TestCaseParameters(this);
+
+ // Special handling for params arguments
+ if (argsNeeded > 0 && argsProvided >= argsNeeded - 1)
+ {
+ IParameterInfo lastParameter = parameters[argsNeeded - 1];
+ Type lastParameterType = lastParameter.ParameterType;
+ Type elementType = lastParameterType.GetElementType();
+
+ if (lastParameterType.IsArray && lastParameter.IsDefined<ParamArrayAttribute>(false))
+ {
+ if (argsProvided == argsNeeded)
+ {
+ Type lastArgumentType = parms.Arguments[argsProvided - 1].GetType();
+ if (!lastParameterType.GetTypeInfo().IsAssignableFrom(lastArgumentType.GetTypeInfo()))
+ {
+ Array array = Array.CreateInstance(elementType, 1);
+ array.SetValue(parms.Arguments[argsProvided - 1], 0);
+ parms.Arguments[argsProvided - 1] = array;
+ }
+ }
+ else
+ {
+ object[] newArglist = new object[argsNeeded];
+ for (int i = 0; i < argsNeeded && i < argsProvided; i++)
+ newArglist[i] = parms.Arguments[i];
+
+ int length = argsProvided - argsNeeded + 1;
+ Array array = Array.CreateInstance(elementType, length);
+ for (int i = 0; i < length; i++)
+ array.SetValue(parms.Arguments[argsNeeded + i - 1], i);
+
+ newArglist[argsNeeded - 1] = array;
+ parms.Arguments = newArglist;
+ argsProvided = argsNeeded;
+ }
+ }
+ }
+
+#if !NETCF
+ //Special handling for optional parameters
+ if (parms.Arguments.Length < argsNeeded)
+ {
+ object[] newArgList = new object[parameters.Length];
+ Array.Copy(parms.Arguments, newArgList, parms.Arguments.Length);
+
+ for (var i = 0; i < parameters.Length; i++)
+ {
+ if (parameters[i].IsOptional)
+ newArgList[i] = Type.Missing;
+ else
+ {
+ if (i < parms.Arguments.Length)
+ newArgList[i] = parms.Arguments[i];
+ else
+ throw new TargetParameterCountException("Incorrect number of parameters specified for TestCase");
+ }
+ }
+ parms.Arguments = newArgList;
+ }
+#endif
+
+ //if (method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(object[]))
+ // parms.Arguments = new object[]{parms.Arguments};
+
+ // Special handling when sole argument is an object[]
+ if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[]))
+ {
+ if (argsProvided > 1 ||
+ argsProvided == 1 && parms.Arguments[0].GetType() != typeof(object[]))
+ {
+ parms.Arguments = new object[] { parms.Arguments };
+ }
+ }
+
+ if (argsProvided == argsNeeded)
+ PerformSpecialConversions(parms.Arguments, parameters);
+ }
+ catch (Exception ex)
+ {
+ parms = new TestCaseParameters(ex);
+ }
+
+ return parms;
+ }
+
+ /// <summary>
+ /// Performs several special conversions allowed by NUnit in order to
+ /// permit arguments with types that cannot be used in the constructor
+ /// of an Attribute such as TestCaseAttribute or to simplify their use.
+ /// </summary>
+ /// <param name="arglist">The arguments to be converted</param>
+ /// <param name="parameters">The ParameterInfo array for the method</param>
+ private static void PerformSpecialConversions(object[] arglist, IParameterInfo[] parameters)
+ {
+ for (int i = 0; i < arglist.Length; i++)
+ {
+ object arg = arglist[i];
+ Type targetType = parameters[i].ParameterType;
+
+ if (arg == null)
+ continue;
+
+ if (arg is SpecialValue && (SpecialValue)arg == SpecialValue.Null)
+ {
+ arglist[i] = null;
+ continue;
+ }
+
+ if (targetType.IsAssignableFrom(arg.GetType()))
+ continue;
+#if !PORTABLE
+ if (arg is DBNull)
+ {
+ arglist[i] = null;
+ continue;
+ }
+#endif
+ bool convert = false;
+
+ if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte) ||
+ targetType == typeof(short?) || targetType == typeof(byte?) || targetType == typeof(sbyte?) || targetType == typeof(double?))
+ {
+ convert = arg is int;
+ }
+ else if (targetType == typeof(decimal) || targetType == typeof(decimal?))
+ {
+ convert = arg is double || arg is string || arg is int;
+ }
+ else if (targetType == typeof(DateTime) || targetType == typeof(DateTime?))
+ {
+ convert = arg is string;
+ }
+
+ if (convert)
+ {
+ Type convertTo = targetType.GetTypeInfo().IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>) ?
+ targetType.GetGenericArguments()[0] : targetType;
+ arglist[i] = Convert.ChangeType(arg, convertTo, System.Globalization.CultureInfo.InvariantCulture);
+ }
+ else
+ // Convert.ChangeType doesn't work for TimeSpan from string
+ if ((targetType == typeof(TimeSpan) || targetType == typeof(TimeSpan?)) && arg is string)
+ {
+ arglist[i] = TimeSpan.Parse((string)arg);
+ }
+ }
+ }
+ #endregion
+
+ #region ITestBuilder Members
+
+ /// <summary>
+ /// Construct one or more TestMethods from a given MethodInfo,
+ /// using available parameter data.
+ /// </summary>
+ /// <param name="method">The MethodInfo for which tests are to be constructed.</param>
+ /// <param name="suite">The suite to which the tests will be added.</param>
+ /// <returns>One or more TestMethods</returns>
+ public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite)
+ {
+ TestMethod test = new NUnitTestCaseBuilder().BuildTestMethod(method, suite, GetParametersForTestCase(method));
+
+#if !PORTABLE
+ if (test.RunState != RunState.NotRunnable &&
+ test.RunState != RunState.Ignored)
+ {
+ PlatformHelper platformHelper = new PlatformHelper();
+
+ if (!platformHelper.IsPlatformSupported(this))
+ {
+ test.RunState = RunState.Skipped;
+ test.Properties.Add(PropertyNames.SkipReason, platformHelper.Reason);
+ }
+ }
+#endif
+
+ yield return test;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.Internal.Builders;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// TestCaseSourceAttribute indicates the source to be used to
+ /// provide test cases for a test method.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
+ public class TestCaseSourceAttribute : NUnitAttribute, ITestBuilder, IImplyFixture
+ {
+
+ private NUnitTestCaseBuilder _builder = new NUnitTestCaseBuilder();
+
+ #region Constructors
+
+ /// <summary>
+ /// Construct with the name of the method, property or field that will provide data
+ /// </summary>
+ /// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
+ public TestCaseSourceAttribute(string sourceName)
+ {
+ this.SourceName = sourceName;
+ }
+
+ /// <summary>
+ /// Construct with a Type and name
+ /// </summary>
+ /// <param name="sourceType">The Type that will provide data</param>
+ /// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
+ /// <param name="methodParams">A set of parameters passed to the method, works only if the Source Name is a method.
+ /// If the source name is a field or property has no effect.</param>
+ public TestCaseSourceAttribute(Type sourceType, string sourceName, object[] methodParams)
+ {
+ this.MethodParams = methodParams;
+ this.SourceType = sourceType;
+ this.SourceName = sourceName;
+ }
+ /// <summary>
+ /// Construct with a Type and name
+ /// </summary>
+ /// <param name="sourceType">The Type that will provide data</param>
+ /// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
+ public TestCaseSourceAttribute(Type sourceType, string sourceName)
+ {
+ this.SourceType = sourceType;
+ this.SourceName = sourceName;
+ }
+
+ /// <summary>
+ /// Construct with a Type
+ /// </summary>
+ /// <param name="sourceType">The type that will provide data</param>
+ public TestCaseSourceAttribute(Type sourceType)
+ {
+ this.SourceType = sourceType;
+ }
+
+ #endregion
+
+ #region Properties
+ /// <summary>
+ /// A set of parameters passed to the method, works only if the Source Name is a method.
+ /// If the source name is a field or property has no effect.
+ /// </summary>
+ public object[] MethodParams { get; private set; }
+ /// <summary>
+ /// The name of a the method, property or fiend to be used as a source
+ /// </summary>
+ public string SourceName { get; private set; }
+
+ /// <summary>
+ /// A Type to be used as a source
+ /// </summary>
+ public Type SourceType { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the category associated with every fixture created from
+ /// this attribute. May be a single category or a comma-separated list.
+ /// </summary>
+ public string Category { get; set; }
+
+ #endregion
+
+ #region ITestBuilder Members
+
+ /// <summary>
+ /// Construct one or more TestMethods from a given MethodInfo,
+ /// using available parameter data.
+ /// </summary>
+ /// <param name="method">The IMethod for which tests are to be constructed.</param>
+ /// <param name="suite">The suite to which the tests will be added.</param>
+ /// <returns>One or more TestMethods</returns>
+ public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite)
+ {
+ foreach (TestCaseParameters parms in GetTestCasesFor(method))
+ yield return _builder.BuildTestMethod(method, suite, parms);
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ /// <summary>
+ /// Returns a set of ITestCaseDataItems for use as arguments
+ /// to a parameterized test method.
+ /// </summary>
+ /// <param name="method">The method for which data is needed.</param>
+ /// <returns></returns>
+ private IEnumerable<ITestCaseData> GetTestCasesFor(IMethodInfo method)
+ {
+ List<ITestCaseData> data = new List<ITestCaseData>();
+
+ try
+ {
+ IEnumerable source = GetTestCaseSource(method);
+
+ if (source != null)
+ {
+ foreach (object item in source)
+ {
+ // First handle two easy cases:
+ // 1. Source is null. This is really an error but if we
+ // throw an exception we simply get an invalid fixture
+ // without good info as to what caused it. Passing a
+ // single null argument will cause an error to be
+ // reported at the test level, in most cases.
+ // 2. User provided an ITestCaseData and we just use it.
+ ITestCaseData parms = item == null
+ ? new TestCaseParameters(new object[] { null })
+ : item as ITestCaseData;
+
+ if (parms == null)
+ {
+ // 3. An array was passed, it may be an object[]
+ // or possibly some other kind of array, which
+ // TestCaseSource can accept.
+ var args = item as object[];
+ if (args == null && item is Array)
+ {
+ Array array = item as Array;
+#if NETCF
+ bool netcfOpenType = method.IsGenericMethodDefinition;
+#else
+ bool netcfOpenType = false;
+#endif
+ int numParameters = netcfOpenType ? array.Length : method.GetParameters().Length;
+ if (array != null && array.Rank == 1 && array.Length == numParameters)
+ {
+ // Array is something like int[] - convert it to
+ // an object[] for use as the argument array.
+ args = new object[array.Length];
+ for (int i = 0; i < array.Length; i++)
+ args[i] = array.GetValue(i);
+ }
+ }
+
+ // Check again if we have an object[]
+ if (args != null)
+ {
+#if NETCF
+ if (method.IsGenericMethodDefinition)
+ {
+ var mi = method.MakeGenericMethodEx(args);
+ if (mi == null)
+ throw new NotSupportedException("Cannot determine generic Type");
+ method = mi;
+ }
+#endif
+
+ var parameters = method.GetParameters();
+ var argsNeeded = parameters.Length;
+ var argsProvided = args.Length;
+
+ // If only one argument is needed, our array may actually
+ // be the bare argument. If it is, we should wrap it in
+ // an outer object[] representing the list of arguments.
+ if (argsNeeded == 1)
+ {
+ var singleParmType = parameters[0].ParameterType;
+
+ if (argsProvided == 0 || typeof(object[]).IsAssignableFrom(singleParmType))
+ {
+ if (argsProvided > 1 || singleParmType.IsAssignableFrom(args.GetType()))
+ {
+ args = new object[] { item };
+ }
+ }
+ }
+ }
+ else // It may be a scalar or a multi-dimensioned array. Wrap it in object[]
+ {
+ args = new object[] { item };
+ }
+
+ parms = new TestCaseParameters(args);
+ }
+
+ if (this.Category != null)
+ foreach (string cat in this.Category.Split(new char[] { ',' }))
+ parms.Properties.Add(PropertyNames.Category, cat);
+
+ data.Add(parms);
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ data.Clear();
+ data.Add(new TestCaseParameters(ex));
+ }
+
+ return data;
+ }
+
+ private IEnumerable GetTestCaseSource(IMethodInfo method)
+ {
+ Type sourceType = SourceType ?? method.TypeInfo.Type;
+
+ // Handle Type implementing IEnumerable separately
+ if (SourceName == null)
+ return Reflect.Construct(sourceType, null) as IEnumerable;
+
+ MemberInfo[] members = sourceType.GetMember(SourceName,
+ BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
+
+ if (members.Length == 1)
+ {
+ MemberInfo member = members[0];
+
+ var field = member as FieldInfo;
+ if (field != null)
+ return field.IsStatic
+ ? (MethodParams == null ? (IEnumerable)field.GetValue(null)
+ : ReturnErrorAsParameter(ParamGivenToField))
+ : ReturnErrorAsParameter(SourceMustBeStatic);
+
+ var property = member as PropertyInfo;
+ if (property != null)
+ return property.GetGetMethod(true).IsStatic
+ ? (MethodParams == null ? (IEnumerable)property.GetValue(null, null)
+ : ReturnErrorAsParameter(ParamGivenToProperty))
+ : ReturnErrorAsParameter(SourceMustBeStatic);
+
+ var m = member as MethodInfo;
+
+
+ if (m != null)
+ return m.IsStatic
+ ? (MethodParams == null || m.GetParameters().Length == MethodParams.Length ? (IEnumerable)m.Invoke(null, MethodParams)
+ : ReturnErrorAsParameter(NumberOfArgsDoesNotMatch))
+ : ReturnErrorAsParameter(SourceMustBeStatic);
+ }
+
+ return null;
+ }
+
+ private static IEnumerable ReturnErrorAsParameter(string errorMessage)
+ {
+ var parms = new TestCaseParameters();
+ parms.RunState = RunState.NotRunnable;
+ parms.Properties.Set(PropertyNames.SkipReason, errorMessage);
+ return new TestCaseParameters[] { parms };
+ }
+
+ private const string SourceMustBeStatic =
+ "The sourceName specified on a TestCaseSourceAttribute must refer to a static field, property or method.";
+ private const string ParamGivenToField = "You have specified a data source field but also given a set of parameters. Fields cannot take parameters, " +
+ "please revise the 3rd parameter passed to the TestCaseSourceAttribute and either remove " +
+ "it or specify a method.";
+ private const string ParamGivenToProperty = "You have specified a data source property but also given a set of parameters. " +
+ "Properties cannot take parameters, please revise the 3rd parameter passed to the " +
+ "TestCaseSource attribute and either remove it or specify a method.";
+ private const string NumberOfArgsDoesNotMatch = "You have given the wrong number of arguments to the method in the TestCaseSourceAttribute" +
+ ", please check the number of parameters passed in the object is correct in the 3rd parameter for the " +
+ "TestCaseSourceAttribute and this matches the number of parameters in the target method and try again.";
+
+#endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.Internal.Builders;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// TestFixtureAttribute is used to mark a class that represents a TestFixture.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class, AllowMultiple=true, Inherited=true)]
+ public class TestFixtureAttribute : NUnitAttribute, IFixtureBuilder, ITestFixtureData
+ {
+ private readonly NUnitTestFixtureBuilder _builder = new NUnitTestFixtureBuilder();
+
+ #region Constructors
+
+ /// <summary>
+ /// Default constructor
+ /// </summary>
+ public TestFixtureAttribute() : this( new object[0] ) { }
+
+ /// <summary>
+ /// Construct with a object[] representing a set of arguments.
+ /// In .NET 2.0, the arguments may later be separated into
+ /// type arguments and constructor arguments.
+ /// </summary>
+ /// <param name="arguments"></param>
+ public TestFixtureAttribute(params object[] arguments)
+ {
+ RunState = RunState.Runnable;
+ Arguments = arguments;
+ TypeArgs = new Type[0];
+ Properties = new PropertyBag();
+ }
+
+ #endregion
+
+ #region ITestData Members
+
+ /// <summary>
+ /// Gets or sets the name of the test.
+ /// </summary>
+ /// <value>The name of the test.</value>
+ public string TestName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the RunState of this test fixture.
+ /// </summary>
+ public RunState RunState { get; private set; }
+
+ /// <summary>
+ /// The arguments originally provided to the attribute
+ /// </summary>
+ public object[] Arguments { get; private set; }
+
+ /// <summary>
+ /// Properties pertaining to this fixture
+ /// </summary>
+ public IPropertyBag Properties { get; private set; }
+
+ #endregion
+
+ #region ITestFixtureData Members
+
+ /// <summary>
+ /// Get or set the type arguments. If not set
+ /// explicitly, any leading arguments that are
+ /// Types are taken as type arguments.
+ /// </summary>
+ public Type[] TypeArgs { get; set; }
+
+ #endregion
+
+ #region Other Properties
+
+ /// <summary>
+ /// Descriptive text for this fixture
+ /// </summary>
+ public string Description
+ {
+ get { return Properties.Get(PropertyNames.Description) as string; }
+ set { Properties.Set(PropertyNames.Description, value); }
+ }
+
+ /// <summary>
+ /// The author of this fixture
+ /// </summary>
+ public string Author
+ {
+ get { return Properties.Get(PropertyNames.Author) as string; }
+ set { Properties.Set(PropertyNames.Author, value); }
+ }
+
+ /// <summary>
+ /// The type that this fixture is testing
+ /// </summary>
+ public Type TestOf
+ {
+ get { return _testOf; }
+ set
+ {
+ _testOf = value;
+ Properties.Set(PropertyNames.TestOf, value.FullName);
+ }
+ }
+ private Type _testOf;
+
+ /// <summary>
+ /// Gets or sets the ignore reason. May set RunState as a side effect.
+ /// </summary>
+ /// <value>The ignore reason.</value>
+ public string Ignore
+ {
+ get { return IgnoreReason; }
+ set { IgnoreReason = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the reason for not running the fixture.
+ /// </summary>
+ /// <value>The reason.</value>
+ public string Reason
+ {
+ get { return this.Properties.Get(PropertyNames.SkipReason) as string; }
+ set { this.Properties.Set(PropertyNames.SkipReason, value); }
+ }
+
+ /// <summary>
+ /// Gets or sets the ignore reason. When set to a non-null
+ /// non-empty value, the test is marked as ignored.
+ /// </summary>
+ /// <value>The ignore reason.</value>
+ public string IgnoreReason
+ {
+ get { return Reason; }
+ set
+ {
+ RunState = RunState.Ignored;
+ Reason = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestFixtureAttribute"/> is explicit.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if explicit; otherwise, <c>false</c>.
+ /// </value>
+ public bool Explicit
+ {
+ get { return RunState == RunState.Explicit; }
+ set { RunState = value ? RunState.Explicit : RunState.Runnable; }
+ }
+
+ /// <summary>
+ /// Gets and sets the category for this fixture.
+ /// May be a comma-separated list of categories.
+ /// </summary>
+ public string Category
+ {
+ get
+ {
+ //return Properties.Get(PropertyNames.Category) as string;
+ var catList = Properties[PropertyNames.Category];
+ if (catList == null)
+ return null;
+
+ switch (catList.Count)
+ {
+ case 0:
+ return null;
+ case 1:
+ return catList[0] as string;
+ default:
+ var cats = new string[catList.Count];
+ int index = 0;
+ foreach (string cat in catList)
+ cats[index++] = cat;
+
+ return string.Join(",", cats);
+ }
+ }
+ set
+ {
+ foreach (string cat in value.Split(new char[] { ',' }))
+ Properties.Add(PropertyNames.Category, cat);
+ }
+ }
+
+ #endregion
+
+ #region IFixtureBuilder Members
+
+ /// <summary>
+ /// Build a fixture from type provided. Normally called for a Type
+ /// on which the attribute has been placed.
+ /// </summary>
+ /// <param name="typeInfo">The type info of the fixture to be used.</param>
+ /// <returns>A an IEnumerable holding one TestFixture object.</returns>
+ public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo)
+ {
+ yield return _builder.BuildFrom(typeInfo, this);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework
+{
+ using System;
+
+ /// <summary>
+ /// Attribute used to identify a method that is
+ /// called before any tests in a fixture are run.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)]
+ [Obsolete("Use OneTimeSetUpAttribute")]
+ public class TestFixtureSetUpAttribute : OneTimeSetUpAttribute
+ {
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.Internal.Builders;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// TestCaseSourceAttribute indicates the source to be used to
+ /// provide test fixture instances for a test class.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
+ public class TestFixtureSourceAttribute : NUnitAttribute, IFixtureBuilder
+ {
+ private readonly NUnitTestFixtureBuilder _builder = new NUnitTestFixtureBuilder();
+
+ /// <summary>
+ /// Error message string is public so the tests can use it
+ /// </summary>
+ public const string MUST_BE_STATIC = "The sourceName specified on a TestCaseSourceAttribute must refer to a static field, property or method.";
+
+ #region Constructors
+
+ /// <summary>
+ /// Construct with the name of the method, property or field that will provide data
+ /// </summary>
+ /// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
+ public TestFixtureSourceAttribute(string sourceName)
+ {
+ this.SourceName = sourceName;
+ }
+
+ /// <summary>
+ /// Construct with a Type and name
+ /// </summary>
+ /// <param name="sourceType">The Type that will provide data</param>
+ /// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
+ public TestFixtureSourceAttribute(Type sourceType, string sourceName)
+ {
+ this.SourceType = sourceType;
+ this.SourceName = sourceName;
+ }
+
+ /// <summary>
+ /// Construct with a Type
+ /// </summary>
+ /// <param name="sourceType">The type that will provide data</param>
+ public TestFixtureSourceAttribute(Type sourceType)
+ {
+ this.SourceType = sourceType;
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// The name of a the method, property or fiend to be used as a source
+ /// </summary>
+ public string SourceName { get; private set; }
+
+ /// <summary>
+ /// A Type to be used as a source
+ /// </summary>
+ public Type SourceType { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the category associated with every fixture created from
+ /// this attribute. May be a single category or a comma-separated list.
+ /// </summary>
+ public string Category { get; set; }
+
+ #endregion
+
+ #region IFixtureBuilder Members
+
+ /// <summary>
+ /// Construct one or more TestFixtures from a given Type,
+ /// using available parameter data.
+ /// </summary>
+ /// <param name="typeInfo">The TypeInfo for which fixures are to be constructed.</param>
+ /// <returns>One or more TestFixtures as TestSuite</returns>
+ public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo)
+ {
+ Type sourceType = SourceType ?? typeInfo.Type;
+
+ foreach (TestFixtureParameters parms in GetParametersFor(sourceType))
+ yield return _builder.BuildFrom(typeInfo, parms);
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ /// <summary>
+ /// Returns a set of ITestFixtureData items for use as arguments
+ /// to a parameterized test fixture.
+ /// </summary>
+ /// <param name="sourceType">The type for which data is needed.</param>
+ /// <returns></returns>
+ public IEnumerable<ITestFixtureData> GetParametersFor(Type sourceType)
+ {
+ List<ITestFixtureData> data = new List<ITestFixtureData>();
+
+ try
+ {
+ IEnumerable source = GetTestFixtureSource(sourceType);
+
+ if (source != null)
+ {
+ foreach (object item in source)
+ {
+ var parms = item as ITestFixtureData;
+
+ if (parms == null)
+ {
+ object[] args = item as object[];
+ if (args == null)
+ {
+ args = new object[] { item };
+ }
+
+ parms = new TestFixtureParameters(args);
+ }
+
+ if (this.Category != null)
+ foreach (string cat in this.Category.Split(new char[] { ',' }))
+ parms.Properties.Add(PropertyNames.Category, cat);
+
+ data.Add(parms);
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ data.Clear();
+ data.Add(new TestFixtureParameters(ex));
+ }
+
+ return data;
+ }
+
+ private IEnumerable GetTestFixtureSource(Type sourceType)
+ {
+ // Handle Type implementing IEnumerable separately
+ if (SourceName == null)
+ return Reflect.Construct(sourceType) as IEnumerable;
+
+ MemberInfo[] members = sourceType.GetMember(SourceName,
+ BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
+
+ if (members.Length == 1)
+ {
+ MemberInfo member = members[0];
+
+ var field = member as FieldInfo;
+ if (field != null)
+ return field.IsStatic
+ ? (IEnumerable)field.GetValue(null)
+ : SourceMustBeStaticError();
+
+ var property = member as PropertyInfo;
+ if (property != null)
+ return property.GetGetMethod(true).IsStatic
+ ? (IEnumerable)property.GetValue(null, null)
+ : SourceMustBeStaticError();
+
+ var m = member as MethodInfo;
+ if (m != null)
+ return m.IsStatic
+ ? (IEnumerable)m.Invoke(null, null)
+ : SourceMustBeStaticError();
+ }
+
+ return null;
+ }
+
+ private static IEnumerable SourceMustBeStaticError()
+ {
+ var parms = new TestFixtureParameters();
+ parms.RunState = RunState.NotRunnable;
+ parms.Properties.Set(PropertyNames.SkipReason, MUST_BE_STATIC);
+ return new TestFixtureParameters[] { parms };
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework
+{
+ using System;
+
+ /// <summary>
+ /// Attribute used to identify a method that is called after
+ /// all the tests in a fixture have run. The method is
+ /// guaranteed to be called, even if an exception is thrown.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)]
+ [Obsolete("Use OneTimeTearDownAttribute")]
+ public class TestFixtureTearDownAttribute : OneTimeTearDownAttribute
+ {
+ }
+}
--- /dev/null
+// **********************************************************************************
+// The MIT License (MIT)
+//
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy of
+// this software and associated documentation files (the "Software"), to deal in
+// the Software without restriction, including without limitation the rights to
+// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+// the Software, and to permit persons to whom the Software is furnished to do so,
+// subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all
+// copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+// **********************************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+
+#region Using Directives
+
+using System;
+using NUnit.Framework.Internal;
+
+#endregion
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Indicates which class the test or test fixture is testing
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
+ public class TestOfAttribute : PropertyAttribute
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestOfAttribute"/> class.
+ /// </summary>
+ /// <param name="type">The type that is being tested.</param>
+ public TestOfAttribute(Type type)
+ : base(PropertyNames.TestOf, type.FullName)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestOfAttribute"/> class.
+ /// </summary>
+ /// <param name="typeName">The type that is being tested.</param>
+ public TestOfAttribute(string typeName)
+ : base(PropertyNames.TestOf, typeName)
+ {
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ using Interfaces;
+ using Internal.Builders;
+
+ /// <summary>
+ /// Adding this attribute to a method within a <seealso cref="TestFixtureAttribute"/>
+ /// class makes the method callable from the NUnit test runner. There is a property
+ /// called Description which is optional which you can provide a more detailed test
+ /// description. This class cannot be inherited.
+ /// </summary>
+ ///
+ /// <example>
+ /// [TestFixture]
+ /// public class Fixture
+ /// {
+ /// [Test]
+ /// public void MethodToTest()
+ /// {}
+ ///
+ /// [Test(Description = "more detailed description")]
+ /// public void TestDescriptionMethod()
+ /// {}
+ /// }
+ /// </example>
+ ///
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited=true)]
+ public class TheoryAttribute : CombiningStrategyAttribute, ITestBuilder, IImplyFixture
+ {
+ /// <summary>
+ /// Construct the attribute, specifying a combining strategy and source of parameter data.
+ /// </summary>
+ public TheoryAttribute() : base(
+ new CombinatorialStrategy(),
+ new ParameterDataProvider(new DatapointProvider(), new ParameterDataSourceProvider()))
+ {
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !PORTABLE
+using System;
+using NUnit.Framework.Internal;
+using NUnit.Framework.Internal.Commands;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Used on a method, marks the test with a timeout value in milliseconds.
+ /// The test will be run in a separate thread and is cancelled if the timeout
+ /// is exceeded. Used on a class or assembly, sets the default timeout
+ /// for all contained test methods.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited=false)]
+ public class TimeoutAttribute : PropertyAttribute, IApplyToContext
+ {
+ private int _timeout;
+
+ /// <summary>
+ /// Construct a TimeoutAttribute given a time in milliseconds
+ /// </summary>
+ /// <param name="timeout">The timeout value in milliseconds</param>
+ public TimeoutAttribute(int timeout)
+ : base(timeout)
+ {
+ _timeout = timeout;
+ }
+
+#region IApplyToContext Members
+
+ void IApplyToContext.ApplyToContext(TestExecutionContext context)
+ {
+ context.TestCaseTimeout = _timeout;
+ }
+
+#endregion
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// ValueSourceAttribute indicates the source to be used to
+ /// provide data for one parameter of a test method.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)]
+ public class ValueSourceAttribute : DataAttribute, IParameterDataSource
+ {
+ #region Constructors
+
+ /// <summary>
+ /// Construct with the name of the factory - for use with languages
+ /// that don't support params arrays.
+ /// </summary>
+ /// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
+ public ValueSourceAttribute(string sourceName)
+ {
+ SourceName = sourceName;
+ }
+
+ /// <summary>
+ /// Construct with a Type and name - for use with languages
+ /// that don't support params arrays.
+ /// </summary>
+ /// <param name="sourceType">The Type that will provide data</param>
+ /// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
+ public ValueSourceAttribute(Type sourceType, string sourceName)
+ {
+ SourceType = sourceType;
+ SourceName = sourceName;
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// The name of a the method, property or fiend to be used as a source
+ /// </summary>
+ public string SourceName { get; private set; }
+
+ /// <summary>
+ /// A Type to be used as a source
+ /// </summary>
+ public Type SourceType { get; private set; }
+
+ #endregion
+
+ #region IParameterDataSource Members
+
+ /// <summary>
+ /// Gets an enumeration of data items for use as arguments
+ /// for a test method parameter.
+ /// </summary>
+ /// <param name="parameter">The parameter for which data is needed</param>
+ /// <returns>
+ /// An enumeration containing individual data items
+ /// </returns>
+ public IEnumerable GetData(IParameterInfo parameter)
+ {
+ return GetDataSource(parameter);
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ private IEnumerable GetDataSource(IParameterInfo parameter)
+ {
+ Type sourceType = SourceType ?? parameter.Method.TypeInfo.Type;
+
+ // TODO: Test this
+ if (SourceName == null)
+ return Reflect.Construct(sourceType) as IEnumerable;
+
+ MemberInfo[] members = sourceType.GetMember(SourceName,
+ BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
+
+ var dataSource = GetDataSourceValue(members);
+
+ if (dataSource == null)
+ {
+ ThrowInvalidDataSourceException();
+ }
+
+ return dataSource;
+ }
+
+ private static IEnumerable GetDataSourceValue(MemberInfo[] members)
+ {
+ if (members.Length != 1) return null;
+
+ MemberInfo member = members[0];
+
+ var field = member as FieldInfo;
+ if (field != null)
+ {
+ if (field.IsStatic)
+ return (IEnumerable)field.GetValue(null);
+
+ ThrowInvalidDataSourceException();
+ }
+
+ var property = member as PropertyInfo;
+ if (property != null)
+ {
+ if (property.GetGetMethod(true).IsStatic)
+ return (IEnumerable)property.GetValue(null, null);
+
+ ThrowInvalidDataSourceException();
+ }
+
+ var m = member as MethodInfo;
+ if (m != null)
+ {
+ if (m.IsStatic)
+ return (IEnumerable)m.Invoke(null, null);
+
+ ThrowInvalidDataSourceException();
+ }
+
+ return null;
+ }
+
+ private static void ThrowInvalidDataSourceException()
+ {
+ throw new InvalidDataSourceException("The sourceName specified on a ValueSourceAttribute must refer to a non null static field, property or method.");
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// ValuesAttribute is used to provide literal arguments for
+ /// an individual parameter of a test.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
+ public class ValuesAttribute : DataAttribute, IParameterDataSource
+ {
+ /// <summary>
+ /// The collection of data to be returned. Must
+ /// be set by any derived attribute classes.
+ /// We use an object[] so that the individual
+ /// elements may have their type changed in GetData
+ /// if necessary
+ /// </summary>
+ // TODO: This causes a lot of boxing so we should eliminate it
+ protected object[] data;
+
+ /// <summary>
+ /// Constructs for use with an Enum parameter. Will pass every enum
+ /// value in to the test.
+ /// </summary>
+ public ValuesAttribute()
+ {
+ data = new object[]{};
+ }
+
+ /// <summary>
+ /// Construct with one argument
+ /// </summary>
+ /// <param name="arg1"></param>
+ public ValuesAttribute(object arg1)
+ {
+ data = new object[] { arg1 };
+ }
+
+ /// <summary>
+ /// Construct with two arguments
+ /// </summary>
+ /// <param name="arg1"></param>
+ /// <param name="arg2"></param>
+ public ValuesAttribute(object arg1, object arg2)
+ {
+ data = new object[] { arg1, arg2 };
+ }
+
+ /// <summary>
+ /// Construct with three arguments
+ /// </summary>
+ /// <param name="arg1"></param>
+ /// <param name="arg2"></param>
+ /// <param name="arg3"></param>
+ public ValuesAttribute(object arg1, object arg2, object arg3)
+ {
+ data = new object[] { arg1, arg2, arg3 };
+ }
+
+ /// <summary>
+ /// Construct with an array of arguments
+ /// </summary>
+ /// <param name="args"></param>
+ public ValuesAttribute(params object[] args)
+ {
+ data = args;
+ }
+
+ /// <summary>
+ /// Get the collection of _values to be used as arguments
+ /// </summary>
+ public IEnumerable GetData(IParameterInfo parameter)
+ {
+ Type targetType = parameter.ParameterType;
+
+ if (targetType.GetTypeInfo().IsEnum && data.Length == 0)
+ {
+ return TypeHelper.GetEnumValues(targetType);
+ }
+ if (targetType == typeof(bool) && data.Length == 0)
+ {
+ return new object[] {true, false};
+ }
+ return GetData(targetType);
+ }
+
+ private IEnumerable GetData(Type targetType)
+ {
+ for (int i = 0; i < data.Length; i++)
+ {
+ object arg = data[i];
+
+ if (arg == null)
+ continue;
+
+ if (arg.GetType().FullName == "NUnit.Framework.SpecialValue" &&
+ arg.ToString() == "Null")
+ {
+ data[i] = null;
+ continue;
+ }
+
+ if (targetType.GetTypeInfo().IsAssignableFrom(arg.GetType().GetTypeInfo()))
+ continue;
+
+#if !PORTABLE
+ if (arg is DBNull)
+ {
+ data[i] = null;
+ continue;
+ }
+#endif
+
+ bool convert = false;
+
+ if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte))
+ convert = arg is int;
+ else
+ if (targetType == typeof(decimal))
+ convert = arg is double || arg is string || arg is int;
+ else
+ if (targetType == typeof(DateTime) || targetType == typeof(TimeSpan))
+ convert = arg is string;
+
+ if (convert)
+ data[i] = Convert.ChangeType(arg, targetType, System.Globalization.CultureInfo.InvariantCulture);
+ }
+
+ return data;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.IO;
+using System.Reflection;
+
+#if NUNIT_ENGINE
+namespace NUnit.Engine.Internal
+#elif NUNIT_FRAMEWORK
+namespace NUnit.Framework.Internal
+#else
+namespace NUnit.Common
+#endif
+{
+ /// <summary>
+ /// AssemblyHelper provides static methods for working
+ /// with assemblies.
+ /// </summary>
+ public class AssemblyHelper
+ {
+ #region GetAssemblyPath
+
+ /// <summary>
+ /// Gets the path from which the assembly defining a type was loaded.
+ /// </summary>
+ /// <param name="type">The Type.</param>
+ /// <returns>The path.</returns>
+ public static string GetAssemblyPath(Type type)
+ {
+#if PORTABLE
+ return GetAssemblyPath(type.GetTypeInfo().Assembly);
+#else
+ return GetAssemblyPath(type.Assembly);
+#endif
+ }
+
+ /// <summary>
+ /// Gets the path from which an assembly was loaded.
+ /// For builds where this is not possible, returns
+ /// the name of the assembly.
+ /// </summary>
+ /// <param name="assembly">The assembly.</param>
+ /// <returns>The path.</returns>
+ public static string GetAssemblyPath(Assembly assembly)
+ {
+#if SILVERLIGHT
+ return GetAssemblyName(assembly).Name;
+#elif NETCF || PORTABLE
+ return assembly.ManifestModule.FullyQualifiedName;
+#else
+ string codeBase = assembly.CodeBase;
+
+ if (IsFileUri(codeBase))
+ return GetAssemblyPathFromCodeBase(codeBase);
+
+ return assembly.Location;
+#endif
+ }
+
+#endregion
+
+#region GetDirectoryName
+
+#if !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Gets the path to the directory from which an assembly was loaded.
+ /// </summary>
+ /// <param name="assembly">The assembly.</param>
+ /// <returns>The path.</returns>
+ public static string GetDirectoryName(Assembly assembly)
+ {
+ return Path.GetDirectoryName(GetAssemblyPath(assembly));
+ }
+#endif
+
+#endregion
+
+#region GetAssemblyName
+
+ /// <summary>
+ /// Gets the AssemblyName of an assembly.
+ /// </summary>
+ /// <param name="assembly">The assembly</param>
+ /// <returns>An AssemblyName</returns>
+ public static AssemblyName GetAssemblyName(Assembly assembly)
+ {
+#if SILVERLIGHT || PORTABLE
+ return new AssemblyName(assembly.FullName);
+#else
+ return assembly.GetName();
+#endif
+ }
+
+ #endregion
+
+ #region Load
+
+#if PORTABLE
+ /// <summary>
+ /// Loads an assembly given a string, which is the AssemblyName
+ /// </summary>
+ /// <param name="name"></param>
+ /// <returns></returns>
+ public static Assembly Load(string name)
+ {
+ var ext = Path.GetExtension(name);
+ if (ext == ".dll" || ext == ".exe")
+ name = Path.GetFileNameWithoutExtension(name);
+
+ return Assembly.Load(new AssemblyName { Name = name });
+ }
+#else
+
+ /// <summary>
+ /// Loads an assembly given a string, which may be the
+ /// path to the assembly or the AssemblyName
+ /// </summary>
+ /// <param name="nameOrPath"></param>
+ /// <returns></returns>
+ public static Assembly Load(string nameOrPath)
+ {
+ var ext = Path.GetExtension(nameOrPath).ToLower();
+
+ // Handle case where this is the path to an assembly
+ if (ext == ".dll" || ext == ".exe")
+ {
+#if SILVERLIGHT
+ return Assembly.Load(Path.GetFileNameWithoutExtension(nameOrPath));
+#elif NETCF
+ return Assembly.LoadFrom(nameOrPath);
+#else
+ return Assembly.Load(AssemblyName.GetAssemblyName(nameOrPath));
+#endif
+ }
+
+ // Assume it's the string representation of an AssemblyName
+ return Assembly.Load(nameOrPath);
+ }
+#endif
+
+ #endregion
+
+#region Helper Methods
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ private static bool IsFileUri(string uri)
+ {
+ return uri.ToLower().StartsWith(Uri.UriSchemeFile);
+ }
+
+ /// <summary>
+ /// Gets the assembly path from code base.
+ /// </summary>
+ /// <remarks>Public for testing purposes</remarks>
+ /// <param name="codeBase">The code base.</param>
+ /// <returns></returns>
+ public static string GetAssemblyPathFromCodeBase(string codeBase)
+ {
+ // Skip over the file:// part
+ int start = Uri.UriSchemeFile.Length + Uri.SchemeDelimiter.Length;
+
+ if (codeBase[start] == '/') // third slash means a local path
+ {
+ // Handle Windows Drive specifications
+ if (codeBase[start + 2] == ':')
+ ++start;
+ // else leave the last slash so path is absolute
+ }
+ else // It's either a Windows Drive spec or a share
+ {
+ if (codeBase[start + 1] != ':')
+ start -= 2; // Back up to include two slashes
+ }
+
+ return codeBase.Substring(start);
+ }
+#endif
+
+#endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Common
+{
+ /// <summary>
+ /// Sets the console color in the constructor and resets it in the dispose
+ /// </summary>
+ public class ColorConsole : IDisposable
+ {
+#if !SILVERLIGHT && !NETCF
+ private ConsoleColor _originalColor;
+#endif
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ColorConsole"/> class.
+ /// </summary>
+ /// <param name="style">The color style to use.</param>
+ public ColorConsole(ColorStyle style)
+ {
+#if !SILVERLIGHT && !NETCF
+ _originalColor = Console.ForegroundColor;
+ Console.ForegroundColor = GetColor(style);
+#endif
+ }
+
+#if !SILVERLIGHT && !NETCF
+ /// <summary>
+ /// By using styles, we can keep everything consistent
+ /// </summary>
+ /// <param name="style"></param>
+ /// <returns></returns>
+ public static ConsoleColor GetColor(ColorStyle style)
+ {
+ ConsoleColor color = GetColorForStyle(style);
+ ConsoleColor bg = Console.BackgroundColor;
+
+ if (color == bg || color == ConsoleColor.Red && bg == ConsoleColor.Magenta)
+ return bg == ConsoleColor.Black
+ ? ConsoleColor.White
+ : ConsoleColor.Black;
+
+ return color;
+ }
+
+ private static ConsoleColor GetColorForStyle(ColorStyle style)
+ {
+ switch (Console.BackgroundColor)
+ {
+ case ConsoleColor.White:
+ switch (style)
+ {
+ case ColorStyle.Header:
+ return ConsoleColor.Black;
+ case ColorStyle.SubHeader:
+ return ConsoleColor.Black;
+ case ColorStyle.SectionHeader:
+ return ConsoleColor.Blue;
+ case ColorStyle.Label:
+ return ConsoleColor.Black;
+ case ColorStyle.Value:
+ return ConsoleColor.Blue;
+ case ColorStyle.Pass:
+ return ConsoleColor.Green;
+ case ColorStyle.Failure:
+ return ConsoleColor.Red;
+ case ColorStyle.Warning:
+ return ConsoleColor.Black;
+ case ColorStyle.Error:
+ return ConsoleColor.Red;
+ case ColorStyle.Output:
+ return ConsoleColor.Black;
+ case ColorStyle.Help:
+ return ConsoleColor.Black;
+ case ColorStyle.Default:
+ default:
+ return ConsoleColor.Black;
+ }
+
+ case ConsoleColor.Cyan:
+ case ConsoleColor.Green:
+ case ConsoleColor.Red:
+ case ConsoleColor.Magenta:
+ case ConsoleColor.Yellow:
+ switch (style)
+ {
+ case ColorStyle.Header:
+ return ConsoleColor.Black;
+ case ColorStyle.SubHeader:
+ return ConsoleColor.Black;
+ case ColorStyle.SectionHeader:
+ return ConsoleColor.Blue;
+ case ColorStyle.Label:
+ return ConsoleColor.Black;
+ case ColorStyle.Value:
+ return ConsoleColor.Black;
+ case ColorStyle.Pass:
+ return ConsoleColor.Black;
+ case ColorStyle.Failure:
+ return ConsoleColor.Red;
+ case ColorStyle.Warning:
+ return ConsoleColor.Yellow;
+ case ColorStyle.Error:
+ return ConsoleColor.Red;
+ case ColorStyle.Output:
+ return ConsoleColor.Black;
+ case ColorStyle.Help:
+ return ConsoleColor.Black;
+ case ColorStyle.Default:
+ default:
+ return ConsoleColor.Black;
+ }
+
+ default:
+ switch (style)
+ {
+ case ColorStyle.Header:
+ return ConsoleColor.White;
+ case ColorStyle.SubHeader:
+ return ConsoleColor.Gray;
+ case ColorStyle.SectionHeader:
+ return ConsoleColor.Cyan;
+ case ColorStyle.Label:
+ return ConsoleColor.Green;
+ case ColorStyle.Value:
+ return ConsoleColor.White;
+ case ColorStyle.Pass:
+ return ConsoleColor.Green;
+ case ColorStyle.Failure:
+ return ConsoleColor.Red;
+ case ColorStyle.Warning:
+ return ConsoleColor.Yellow;
+ case ColorStyle.Error:
+ return ConsoleColor.Red;
+ case ColorStyle.Output:
+ return ConsoleColor.Gray;
+ case ColorStyle.Help:
+ return ConsoleColor.Green;
+ case ColorStyle.Default:
+ default:
+ return ConsoleColor.Green;
+ }
+ }
+ }
+#endif
+
+ #region Implementation of IDisposable
+
+ /// <summary>
+ /// If color is enabled, restores the console colors to their defaults
+ /// </summary>
+ public void Dispose()
+ {
+#if !SILVERLIGHT && !NETCF
+ Console.ForegroundColor = _originalColor;
+#endif
+ }
+
+ #endregion
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.IO;
+using System.Text;
+
+namespace NUnit.Common
+{
+ public class ColorConsoleWriter : ExtendedTextWrapper
+ {
+ public bool _colorEnabled;
+
+ /// <summary>
+ /// Construct a ColorConsoleWriter.
+ /// </summary>
+ public ColorConsoleWriter() : this(true) { }
+
+ /// <summary>
+ /// Construct a ColorConsoleWriter.
+ /// </summary>
+ /// <param name="colorEnabled">Flag indicating whether color should be enabled</param>
+ public ColorConsoleWriter(bool colorEnabled)
+ : base(Console.Out)
+ {
+ _colorEnabled = colorEnabled;
+ }
+
+ #region Extended Methods
+ /// <summary>
+ /// Writes the value with the specified style.
+ /// </summary>
+ /// <param name="style">The style.</param>
+ /// <param name="value">The value.</param>
+ public override void Write(ColorStyle style, string value)
+ {
+ if (_colorEnabled)
+ using (new ColorConsole(style))
+ {
+ Write(value);
+ }
+ else
+ Write(value);
+ }
+
+ /// <summary>
+ /// Writes the value with the specified style.
+ /// </summary>
+ /// <param name="style">The style.</param>
+ /// <param name="value">The value.</param>
+ public override void WriteLine(ColorStyle style, string value)
+ {
+ if (_colorEnabled)
+ using (new ColorConsole(style))
+ {
+ WriteLine(value);
+ }
+ else
+ WriteLine(value);
+ }
+
+ /// <summary>
+ /// Writes the label and the option that goes with it.
+ /// </summary>
+ /// <param name="label">The label.</param>
+ /// <param name="option">The option.</param>
+ public override void WriteLabel(string label, object option)
+ {
+ WriteLabel(label, option, ColorStyle.Value);
+ }
+
+ /// <summary>
+ /// Writes the label and the option that goes with it followed by a new line.
+ /// </summary>
+ /// <param name="label">The label.</param>
+ /// <param name="option">The option.</param>
+ public override void WriteLabelLine(string label, object option)
+ {
+ WriteLabelLine(label, option, ColorStyle.Value);
+ }
+
+ /// <summary>
+ /// Writes the label and the option that goes with it and optionally writes a new line.
+ /// </summary>
+ /// <param name="label">The label.</param>
+ /// <param name="option">The option.</param>
+ /// <param name="valueStyle">The color to display the value with</param>
+ public override void WriteLabel(string label, object option, ColorStyle valueStyle)
+ {
+ Write(ColorStyle.Label, label);
+ Write(valueStyle, option.ToString());
+ }
+
+ /// <summary>
+ /// Writes the label and the option that goes with it followed by a new line.
+ /// </summary>
+ /// <param name="label">The label.</param>
+ /// <param name="option">The option.</param>
+ /// <param name="valueStyle">The color to display the value with</param>
+ public override void WriteLabelLine(string label, object option, ColorStyle valueStyle)
+ {
+ WriteLabel(label, option, valueStyle);
+ WriteLine();
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Common
+{
+ /// <summary>
+ /// ColorStyle enumerates the various styles used in the console display
+ /// </summary>
+ public enum ColorStyle
+ {
+ /// <summary>
+ /// Color for headers
+ /// </summary>
+ Header,
+ /// <summary>
+ /// Color for sub-headers
+ /// </summary>
+ SubHeader,
+ /// <summary>
+ /// Color for each of the section headers
+ /// </summary>
+ SectionHeader,
+ /// <summary>
+ /// The default color for items that don't fit into the other categories
+ /// </summary>
+ Default,
+ /// <summary>
+ /// Test output
+ /// </summary>
+ Output,
+ /// <summary>
+ /// Color for help text
+ /// </summary>
+ Help,
+ /// <summary>
+ /// Color for labels
+ /// </summary>
+ Label,
+ /// <summary>
+ /// Color for values, usually go beside labels
+ /// </summary>
+ Value,
+ /// <summary>
+ /// Color for passed tests
+ /// </summary>
+ Pass,
+ /// <summary>
+ /// Color for failed tests
+ /// </summary>
+ Failure,
+ /// <summary>
+ /// Color for warnings, ignored or skipped tests
+ /// </summary>
+ Warning,
+ /// <summary>
+ /// Color for errors and exceptions
+ /// </summary>
+ Error
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.IO;
+using NUnit.Options;
+
+namespace NUnit.Common
+{
+ /// <summary>
+ /// CommandLineOptions is the base class the specific option classes
+ /// used for nunit3-console and nunitlite. It encapsulates all common
+ /// settings and features of both. This is done to ensure that common
+ /// features remain common and for the convenience of having the code
+ /// in a common location. The class inherits from the Mono
+ /// Options OptionSet class and provides a central location
+ /// for defining and parsing options.
+ /// </summary>
+ public class CommandLineOptions : OptionSet
+ {
+ private bool validated;
+#if !PORTABLE
+ private bool noresult;
+#endif
+
+ #region Constructor
+
+ internal CommandLineOptions(IDefaultOptionsProvider defaultOptionsProvider, params string[] args)
+ {
+ // Apply default options
+ if (defaultOptionsProvider == null) throw new ArgumentNullException("defaultOptionsProvider");
+#if !PORTABLE
+ TeamCity = defaultOptionsProvider.TeamCity;
+#endif
+
+ ConfigureOptions();
+ if (args != null)
+ Parse(args);
+ }
+
+ public CommandLineOptions(params string[] args)
+ {
+ ConfigureOptions();
+ if (args != null)
+ Parse(args);
+ }
+
+ #endregion
+
+ #region Properties
+
+ // Action to Perform
+
+ public bool Explore { get; private set; }
+
+ public bool ShowHelp { get; private set; }
+
+ public bool ShowVersion { get; private set; }
+
+ // Select tests
+
+ private List<string> inputFiles = new List<string>();
+ public IList<string> InputFiles { get { return inputFiles; } }
+
+ private List<string> testList = new List<string>();
+ public IList<string> TestList { get { return testList; } }
+
+ public string TestParameters { get; private set; }
+
+ public string WhereClause { get; private set; }
+ public bool WhereClauseSpecified { get { return WhereClause != null; } }
+
+ private int defaultTimeout = -1;
+ public int DefaultTimeout { get { return defaultTimeout; } }
+ public bool DefaultTimeoutSpecified { get { return defaultTimeout >= 0; } }
+
+ private int randomSeed = -1;
+ public int RandomSeed { get { return randomSeed; } }
+ public bool RandomSeedSpecified { get { return randomSeed >= 0; } }
+
+ public string DefaultTestNamePattern { get; private set; }
+
+ private int numWorkers = -1;
+ public int NumberOfTestWorkers { get { return numWorkers; } }
+ public bool NumberOfTestWorkersSpecified { get { return numWorkers >= 0; } }
+
+ public bool StopOnError { get; private set; }
+
+ public bool WaitBeforeExit { get; private set; }
+
+ // Output Control
+
+ public bool NoHeader { get; private set; }
+
+ public bool NoColor { get; private set; }
+
+ public bool Verbose { get; private set; }
+
+ public bool TeamCity { get; private set; }
+
+ public string OutFile { get; private set; }
+ public bool OutFileSpecified { get { return OutFile != null; } }
+
+ public string ErrFile { get; private set; }
+ public bool ErrFileSpecified { get { return ErrFile != null; } }
+
+ public string DisplayTestLabels { get; private set; }
+
+#if !PORTABLE
+ private string workDirectory = null;
+ public string WorkDirectory
+ {
+ get { return workDirectory ?? NUnit.Env.DefaultWorkDirectory; }
+ }
+ public bool WorkDirectorySpecified { get { return workDirectory != null; } }
+#endif
+
+ public string InternalTraceLevel { get; private set; }
+ public bool InternalTraceLevelSpecified { get { return InternalTraceLevel != null; } }
+
+ /// <summary>Indicates whether a full report should be displayed.</summary>
+ public bool Full { get; private set; }
+
+#if !PORTABLE
+ private List<OutputSpecification> resultOutputSpecifications = new List<OutputSpecification>();
+ public IList<OutputSpecification> ResultOutputSpecifications
+ {
+ get
+ {
+ if (noresult)
+ return new OutputSpecification[0];
+
+ if (resultOutputSpecifications.Count == 0)
+ resultOutputSpecifications.Add(new OutputSpecification("TestResult.xml"));
+
+ return resultOutputSpecifications;
+ }
+ }
+
+ private List<OutputSpecification> exploreOutputSpecifications = new List<OutputSpecification>();
+ public IList<OutputSpecification> ExploreOutputSpecifications { get { return exploreOutputSpecifications; } }
+#endif
+ // Error Processing
+
+ public List<string> errorMessages = new List<string>();
+ public IList<string> ErrorMessages { get { return errorMessages; } }
+
+#endregion
+
+#region Public Methods
+
+ public bool Validate()
+ {
+ if (!validated)
+ {
+ CheckOptionCombinations();
+
+ validated = true;
+ }
+
+ return ErrorMessages.Count == 0;
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ protected virtual void CheckOptionCombinations()
+ {
+
+ }
+
+ /// <summary>
+ /// Case is ignored when val is compared to validValues. When a match is found, the
+ /// returned value will be in the canonical case from validValues.
+ /// </summary>
+ protected string RequiredValue(string val, string option, params string[] validValues)
+ {
+ if (string.IsNullOrEmpty(val))
+ ErrorMessages.Add("Missing required value for option '" + option + "'.");
+
+ bool isValid = true;
+
+ if (validValues != null && validValues.Length > 0)
+ {
+ isValid = false;
+
+ foreach (string valid in validValues)
+ if (string.Compare(valid, val, StringComparison.OrdinalIgnoreCase) == 0)
+ return valid;
+
+ }
+
+ if (!isValid)
+ ErrorMessages.Add(string.Format("The value '{0}' is not valid for option '{1}'.", val, option));
+
+ return val;
+ }
+
+ protected int RequiredInt(string val, string option)
+ {
+ // We have to return something even though the value will
+ // be ignored if an error is reported. The -1 value seems
+ // like a safe bet in case it isn't ignored due to a bug.
+ int result = -1;
+
+ if (string.IsNullOrEmpty(val))
+ ErrorMessages.Add("Missing required value for option '" + option + "'.");
+ else
+ {
+ // NOTE: Don't replace this with TryParse or you'll break the CF build!
+ try
+ {
+ result = int.Parse(val);
+ }
+ catch (Exception)
+ {
+ ErrorMessages.Add("An int value was expected for option '{0}' but a value of '{1}' was used");
+ }
+ }
+
+ return result;
+ }
+
+ private string ExpandToFullPath(string path)
+ {
+ if (path == null) return null;
+
+#if NETCF || PORTABLE
+ return Path.Combine(NUnit.Env.DocumentFolder, path);
+#else
+ return Path.GetFullPath(path);
+#endif
+ }
+
+ protected virtual void ConfigureOptions()
+ {
+ // NOTE: The order in which patterns are added
+ // determines the display order for the help.
+
+ // Select Tests
+ this.Add("test=", "Comma-separated list of {NAMES} of tests to run or explore. This option may be repeated.",
+ v => ((List<string>)TestList).AddRange(TestNameParser.Parse(RequiredValue(v, "--test"))));
+#if !PORTABLE
+ this.Add("testlist=", "File {PATH} containing a list of tests to run, one per line. This option may be repeated.",
+ v =>
+ {
+ string testListFile = RequiredValue(v, "--testlist");
+
+ var fullTestListPath = ExpandToFullPath(testListFile);
+
+ if (!File.Exists(fullTestListPath))
+ ErrorMessages.Add("Unable to locate file: " + testListFile);
+ else
+ {
+ try
+ {
+ using (var rdr = new StreamReader(fullTestListPath))
+ {
+ while (!rdr.EndOfStream)
+ {
+ var line = rdr.ReadLine().Trim();
+
+ if (!string.IsNullOrEmpty(line) && line[0] != '#')
+ ((List<string>)TestList).Add(line);
+ }
+ }
+ }
+ catch (IOException)
+ {
+ ErrorMessages.Add("Unable to read file: " + testListFile);
+ }
+ }
+ });
+
+#endif
+ this.Add("where=", "Test selection {EXPRESSION} indicating what tests will be run. See description below.",
+ v => WhereClause = RequiredValue(v, "--where"));
+
+ this.Add("params|p=", "Define a test parameter.",
+ v =>
+ {
+ string parameters = RequiredValue( v, "--params");
+
+ foreach (string param in parameters.Split(new[] { ';' }))
+ {
+ if (!param.Contains("="))
+ ErrorMessages.Add("Invalid format for test parameter. Use NAME=VALUE.");
+ }
+
+ if (TestParameters == null)
+ TestParameters = parameters;
+ else
+ TestParameters += ";" + parameters;
+ });
+
+ this.Add("timeout=", "Set timeout for each test case in {MILLISECONDS}.",
+ v => defaultTimeout = RequiredInt(v, "--timeout"));
+
+ this.Add("seed=", "Set the random {SEED} used to generate test cases.",
+ v => randomSeed = RequiredInt(v, "--seed"));
+#if !PORTABLE
+ this.Add("workers=", "Specify the {NUMBER} of worker threads to be used in running tests. If not specified, defaults to 2 or the number of processors, whichever is greater.",
+ v => numWorkers = RequiredInt(v, "--workers"));
+#endif
+ this.Add("stoponerror", "Stop run immediately upon any test failure or error.",
+ v => StopOnError = v != null);
+
+ this.Add("wait", "Wait for input before closing console window.",
+ v => WaitBeforeExit = v != null);
+#if !PORTABLE
+ // Output Control
+ this.Add("work=", "{PATH} of the directory to use for output files. If not specified, defaults to the current directory.",
+ v => workDirectory = RequiredValue(v, "--work"));
+
+ this.Add("output|out=", "File {PATH} to contain text output from the tests.",
+ v => OutFile = RequiredValue(v, "--output"));
+
+ this.Add("err=", "File {PATH} to contain error output from the tests.",
+ v => ErrFile = RequiredValue(v, "--err"));
+
+ this.Add("full", "Prints full report of all test results.",
+ v => Full = v != null);
+
+ this.Add("result=", "An output {SPEC} for saving the test results.\nThis option may be repeated.",
+ v => resultOutputSpecifications.Add(new OutputSpecification(RequiredValue(v, "--resultxml"))));
+
+ this.Add("explore:", "Display or save test info rather than running tests. Optionally provide an output {SPEC} for saving the test info. This option may be repeated.", v =>
+ {
+ Explore = true;
+ if (v != null)
+ ExploreOutputSpecifications.Add(new OutputSpecification(v));
+ });
+
+ this.Add("noresult", "Don't save any test results.",
+ v => noresult = v != null);
+#endif
+ this.Add("labels=", "Specify whether to write test case names to the output. Values: Off, On, All",
+ v => DisplayTestLabels = RequiredValue(v, "--labels", "Off", "On", "All"));
+
+ this.Add("test-name-format=", "Non-standard naming pattern to use in generating test names.",
+ v => DefaultTestNamePattern = RequiredValue(v, "--test-name-format"));
+
+#if !PORTABLE
+ this.Add("trace=", "Set internal trace {LEVEL}.\nValues: Off, Error, Warning, Info, Verbose (Debug)",
+ v => InternalTraceLevel = RequiredValue(v, "--trace", "Off", "Error", "Warning", "Info", "Verbose", "Debug"));
+
+#if !NETCF
+ this.Add("teamcity", "Turns on use of TeamCity service messages.",
+ v => TeamCity = v != null);
+#endif
+
+ this.Add("noheader|noh", "Suppress display of program information at start of run.",
+ v => NoHeader = v != null);
+
+ this.Add("nocolor|noc", "Displays console output without color.",
+ v => NoColor = v != null);
+#endif
+ this.Add("verbose|v", "Display additional information as the test runs.",
+ v => Verbose = v != null);
+
+ this.Add("help|h", "Display this message and exit.",
+ v => ShowHelp = v != null);
+
+ this.Add("version|V", "Display the header and exit.",
+ v => ShowVersion = v != null);
+
+ // Default
+ this.Add("<>", v =>
+ {
+#if PORTABLE
+ if (v.StartsWith("-") || v.StartsWith("/") && Environment.NewLine == "\r\n")
+#else
+ if (v.StartsWith("-") || v.StartsWith("/") && Path.DirectorySeparatorChar != '/')
+#endif
+ ErrorMessages.Add("Invalid argument: " + v);
+ else
+ InputFiles.Add(v);
+ });
+ }
+
+#endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Text;
+
+namespace NUnit
+{
+ /// <summary>
+ /// Env is a static class that provides some of the features of
+ /// System.Environment that are not available under all runtimes
+ /// </summary>
+ public class Env
+ {
+ // Define NewLine to be used for this system
+ // NOTE: Since this is done at compile time for .NET CF,
+ // these binaries are not yet currently portable.
+ /// <summary>
+ /// The newline sequence in the current environment.
+ /// </summary>
+#if PocketPC || WindowsCE || NETCF
+ public static readonly string NewLine = "\r\n";
+#else
+ public static readonly string NewLine = Environment.NewLine;
+#endif
+
+ /// <summary>
+ /// Path to the 'My Documents' folder
+ /// </summary>
+#if PocketPC || WindowsCE || NETCF || PORTABLE
+ public static string DocumentFolder = @"\My Documents";
+#else
+ public static string DocumentFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
+#endif
+ /// <summary>
+ /// Directory used for file output if not specified on commandline.
+ /// </summary>
+#if SILVERLIGHT || PocketPC || WindowsCE || NETCF || PORTABLE
+ public static readonly string DefaultWorkDirectory = DocumentFolder;
+#else
+ public static readonly string DefaultWorkDirectory = Environment.CurrentDirectory;
+#endif
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using NUnit.Framework.TUnit;
+using System.IO;
+using System.Text;
+
+namespace NUnit.Common
+{
+ /// <summary>
+ /// ExtendedTextWrapper wraps a TextWriter and makes it
+ /// look like an ExtendedTextWriter. All style indications
+ /// are ignored. It's used when text is being written
+ /// to a file.
+ /// </summary>
+ public class ExtendedTextWrapper : ExtendedTextWriter
+ {
+ private TextWriter _writer;
+
+ public ExtendedTextWrapper(TextWriter writer)
+ {
+ _writer = writer;
+ }
+
+ #region TextWriter Overrides
+
+ /// <summary>
+ /// Write a single char value
+ /// </summary>
+ public override void Write(char value)
+ {
+ _writer.Write(value);
+ }
+
+ /// <summary>
+ /// Write a string value
+ /// </summary>
+ public override void Write(string value)
+ {
+ _writer.Write(value);
+ }
+
+ /// <summary>
+ /// Write a string value followed by a NewLine
+ /// </summary>
+ public override void WriteLine(string value)
+ {
+ _writer.WriteLine(TLogger.DefaultTag + value);
+ }
+
+ /// <summary>
+ /// Gets the encoding for this ExtendedTextWriter
+ /// </summary>
+ public override Encoding Encoding
+ {
+ get { return _writer.Encoding; }
+ }
+
+ /// <summary>
+ /// Dispose the Extended TextWriter
+ /// </summary>
+ protected override void Dispose(bool disposing)
+ {
+ _writer.Dispose();
+ }
+
+ #endregion
+
+ #region Extended Methods
+
+ /// <summary>
+ /// Writes the value with the specified style.
+ /// </summary>
+ /// <param name="style">The style.</param>
+ /// <param name="value">The value.</param>
+ public override void Write(ColorStyle style, string value)
+ {
+ Write(value);
+ }
+
+ /// <summary>
+ /// Writes the value with the specified style
+ /// </summary>
+ /// <param name="style">The style.</param>
+ /// <param name="value">The value.</param>
+ public override void WriteLine(ColorStyle style, string value)
+ {
+ WriteLine(value);
+ }
+
+ /// <summary>
+ /// Writes the label and the option that goes with it.
+ /// </summary>
+ /// <param name="label">The label.</param>
+ /// <param name="option">The option.</param>
+ public override void WriteLabel(string label, object option)
+ {
+ Write(label);
+ Write(option.ToString());
+ }
+
+ /// <summary>
+ /// Writes the label and the option that goes with it.
+ /// </summary>
+ /// <param name="label">The label.</param>
+ /// <param name="option">The option.</param>
+ /// <param name="valueStyle">The color to display the value with</param>
+ public override void WriteLabel(string label, object option, ColorStyle valueStyle)
+ {
+ WriteLabel(label, option);
+ }
+
+ /// <summary>
+ /// Writes the label and the option that goes with it followed by a new line.
+ /// </summary>
+ /// <param name="label">The label.</param>
+ /// <param name="option">The option.</param>
+ public override void WriteLabelLine(string label, object option)
+ {
+ WriteLabel(label, option);
+ WriteLine();
+ }
+
+ /// <summary>
+ /// Writes the label and the option that goes with it followed by a new line.
+ /// </summary>
+ /// <param name="label">The label.</param>
+ /// <param name="option">The option.</param>
+ /// <param name="valueStyle">The color to display the value with</param>
+ public override void WriteLabelLine(string label, object option, ColorStyle valueStyle)
+ {
+ WriteLabelLine(label, option);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.IO;
+
+namespace NUnit.Common
+{
+ /// <summary>
+ /// ExtendedTextWriter extends the TextWriter abstract class
+ /// to support displaying text in color.
+ /// $</summary>
+ public abstract class ExtendedTextWriter : TextWriter
+ {
+ #region Extended Methods
+
+ /// <summary>
+ /// Writes the value with the specified style.
+ /// </summary>
+ /// <param name="style">The style.</param>
+ /// <param name="value">The value.</param>
+ public abstract void Write(ColorStyle style, string value);
+
+ /// <summary>
+ /// Writes the value with the specified style
+ /// </summary>
+ /// <param name="style">The style.</param>
+ /// <param name="value">The value.</param>
+ public abstract void WriteLine(ColorStyle style, string value);
+
+ /// <summary>
+ /// Writes the label and the option that goes with it.
+ /// </summary>
+ /// <param name="label">The label.</param>
+ /// <param name="option">The option.</param>
+ public abstract void WriteLabel(string label, object option);
+
+ /// <summary>
+ /// Writes the label and the option that goes with it.
+ /// </summary>
+ /// <param name="label">The label.</param>
+ /// <param name="option">The option.</param>
+ /// <param name="valueStyle">The color to display the value with</param>
+ public abstract void WriteLabel(string label, object option, ColorStyle valueStyle);
+
+ /// <summary>
+ /// Writes the label and the option that goes with it followed by a new line.
+ /// </summary>
+ /// <param name="label">The label.</param>
+ /// <param name="option">The option.</param>
+ public abstract void WriteLabelLine(string label, object option);
+
+ /// <summary>
+ /// Writes the label and the option that goes with it followed by a new line.
+ /// </summary>
+ /// <param name="label">The label.</param>
+ /// <param name="option">The option.</param>
+ /// <param name="valueStyle">The color to display the value with</param>
+ public abstract void WriteLabelLine(string label, object option, ColorStyle valueStyle);
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit
+{
+ /// <summary>
+ /// Class used to guard against unexpected argument values
+ /// or operations by throwing an appropriate exception.
+ /// </summary>
+ static class Guard
+ {
+ /// <summary>
+ /// Throws an exception if an argument is null
+ /// </summary>
+ /// <param name="value">The value to be tested</param>
+ /// <param name="name">The name of the argument</param>
+ public static void ArgumentNotNull(object value, string name)
+ {
+ if (value == null)
+ throw new ArgumentNullException("Argument " + name + " must not be null", name);
+ }
+
+ /// <summary>
+ /// Throws an exception if a string argument is null or empty
+ /// </summary>
+ /// <param name="value">The value to be tested</param>
+ /// <param name="name">The name of the argument</param>
+ public static void ArgumentNotNullOrEmpty(string value, string name)
+ {
+ ArgumentNotNull(value, name);
+
+ if (value == string.Empty)
+ throw new ArgumentException("Argument " + name +" must not be the empty string", name);
+ }
+
+ /// <summary>
+ /// Throws an ArgumentOutOfRangeException if the specified condition is not met.
+ /// </summary>
+ /// <param name="condition">The condition that must be met</param>
+ /// <param name="message">The exception message to be used</param>
+ /// <param name="paramName">The name of the argument</param>
+ public static void ArgumentInRange(bool condition, string message, string paramName)
+ {
+ if (!condition)
+ throw new ArgumentOutOfRangeException(paramName, message);
+ }
+
+ /// <summary>
+ /// Throws an ArgumentException if the specified condition is not met.
+ /// </summary>
+ /// <param name="condition">The condition that must be met</param>
+ /// <param name="message">The exception message to be used</param>
+ /// <param name="paramName">The name of the argument</param>
+ public static void ArgumentValid(bool condition, string message, string paramName)
+ {
+ if (!condition)
+ throw new ArgumentException(message, paramName);
+ }
+
+ /// <summary>
+ /// Throws an InvalidOperationException if the specified condition is not met.
+ /// </summary>
+ /// <param name="condition">The condition that must be met</param>
+ /// <param name="message">The exception message to be used</param>
+ public static void OperationValid(bool condition, string message)
+ {
+ if (!condition)
+ throw new InvalidOperationException(message);
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Common
+{
+ internal interface IDefaultOptionsProvider
+ {
+ bool TeamCity { get; }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+#if NUNIT_ENGINE
+namespace NUnit.Engine
+#elif NUNIT_FRAMEWORK
+namespace NUnit.Framework.Internal
+#else
+namespace NUnit.Common
+#endif
+{
+ /// <summary>
+ /// Interface for logging within the engine
+ /// </summary>
+ public interface ILogger
+ {
+ /// <summary>
+ /// Logs the specified message at the error level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ void Error(string message);
+
+ /// <summary>
+ /// Logs the specified message at the error level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="args">The arguments.</param>
+ void Error(string message, params object[] args);
+
+ /// <summary>
+ /// Logs the specified message at the warning level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ void Warning(string message);
+
+ /// <summary>
+ /// Logs the specified message at the warning level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="args">The arguments.</param>
+ void Warning(string message, params object[] args);
+
+ /// <summary>
+ /// Logs the specified message at the info level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ void Info(string message);
+
+ /// <summary>
+ /// Logs the specified message at the info level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="args">The arguments.</param>
+ void Info(string message, params object[] args);
+
+ /// <summary>
+ /// Logs the specified message at the debug level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ void Debug(string message);
+
+ /// <summary>
+ /// Logs the specified message at the debug level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="args">The arguments.</param>
+ void Debug(string message, params object[] args);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2013 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.IO;
+
+#if NUNIT_ENGINE
+namespace NUnit.Engine.Internal
+#elif NUNIT_FRAMEWORK
+namespace NUnit.Framework.Internal
+#else
+namespace NUnit.Common
+#endif
+{
+ /// <summary>
+ /// InternalTrace provides facilities for tracing the execution
+ /// of the NUnit framework. Tests and classes under test may make use
+ /// of Console writes, System.Diagnostics.Trace or various loggers and
+ /// NUnit itself traps and processes each of them. For that reason, a
+ /// separate internal trace is needed.
+ ///
+ /// Note:
+ /// InternalTrace uses a global lock to allow multiple threads to write
+ /// trace messages. This can easily make it a bottleneck so it must be
+ /// used sparingly. Keep the trace Level as low as possible and only
+ /// insert InternalTrace writes where they are needed.
+ /// TODO: add some buffering and a separate writer thread as an option.
+ /// TODO: figure out a way to turn on trace in specific classes only.
+ /// </summary>
+ public static class InternalTrace
+ {
+ private static InternalTraceLevel traceLevel;
+ private static InternalTraceWriter traceWriter;
+
+ /// <summary>
+ /// Gets a flag indicating whether the InternalTrace is initialized
+ /// </summary>
+ public static bool Initialized { get; private set; }
+
+#if !PORTABLE
+ /// <summary>
+ /// Initialize the internal trace facility using the name of the log
+ /// to be written to and the trace level.
+ /// </summary>
+ /// <param name="logName">The log name</param>
+ /// <param name="level">The trace level</param>
+ public static void Initialize(string logName, InternalTraceLevel level)
+ {
+ if (!Initialized)
+ {
+ traceLevel = level;
+
+ if (traceWriter == null && traceLevel > InternalTraceLevel.Off)
+ {
+ traceWriter = new InternalTraceWriter(logName);
+ traceWriter.WriteLine("InternalTrace: Initializing at level {0}", traceLevel);
+ }
+
+ Initialized = true;
+ }
+ else
+ traceWriter.WriteLine("InternalTrace: Ignoring attempted re-initialization at level {0}", level);
+ }
+#endif
+
+ /// <summary>
+ /// Initialize the internal trace using a provided TextWriter and level
+ /// </summary>
+ /// <param name="writer">A TextWriter</param>
+ /// <param name="level">The InternalTraceLevel</param>
+ public static void Initialize(TextWriter writer, InternalTraceLevel level)
+ {
+ if (!Initialized)
+ {
+ traceLevel = level;
+
+ if (traceWriter == null && traceLevel > InternalTraceLevel.Off)
+ {
+ traceWriter = new InternalTraceWriter(writer);
+ traceWriter.WriteLine("InternalTrace: Initializing at level " + traceLevel.ToString());
+ }
+
+ Initialized = true;
+ }
+ }
+
+ /// <summary>
+ /// Get a named Logger
+ /// </summary>
+ /// <returns></returns>
+ public static Logger GetLogger(string name)
+ {
+ return new Logger(name, traceLevel, traceWriter);
+ }
+
+ /// <summary>
+ /// Get a logger named for a particular Type.
+ /// </summary>
+ public static Logger GetLogger(Type type)
+ {
+ return GetLogger(type.FullName);
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if NUNIT_ENGINE
+namespace NUnit.Engine
+#elif NUNIT_FRAMEWORK
+namespace NUnit.Framework.Internal
+#else
+namespace NUnit.Common
+#endif
+{
+ /// <summary>
+ /// InternalTraceLevel is an enumeration controlling the
+ /// level of detailed presented in the internal log.
+ /// </summary>
+ public enum InternalTraceLevel
+ {
+ /// <summary>
+ /// Use the default settings as specified by the user.
+ /// </summary>
+ Default,
+
+ /// <summary>
+ /// Do not display any trace messages
+ /// </summary>
+ Off,
+
+ /// <summary>
+ /// Display Error messages only
+ /// </summary>
+ Error,
+
+ /// <summary>
+ /// Display Warning level and higher messages
+ /// </summary>
+ Warning,
+
+ /// <summary>
+ /// Display informational and higher messages
+ /// </summary>
+ Info,
+
+ /// <summary>
+ /// Display debug messages and higher - i.e. all messages
+ /// </summary>
+ Debug,
+
+ /// <summary>
+ /// Display debug messages and higher - i.e. all messages
+ /// </summary>
+ Verbose = Debug
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2013 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.IO;
+
+#if NUNIT_ENGINE
+namespace NUnit.Engine.Internal
+#elif NUNIT_FRAMEWORK
+namespace NUnit.Framework.Internal
+#else
+namespace NUnit.Common
+#endif
+{
+ /// <summary>
+ /// A trace listener that writes to a separate file per domain
+ /// and process using it.
+ /// </summary>
+ public class InternalTraceWriter : TextWriter
+ {
+ TextWriter writer;
+ object myLock = new object();
+
+#if !PORTABLE
+ /// <summary>
+ /// Construct an InternalTraceWriter that writes to a file.
+ /// </summary>
+ /// <param name="logPath">Path to the file to use</param>
+ public InternalTraceWriter(string logPath)
+ {
+ var streamWriter = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.Write));
+ streamWriter.AutoFlush = true;
+ this.writer = streamWriter;
+ }
+#endif
+
+ /// <summary>
+ /// Construct an InternalTraceWriter that writes to a
+ /// TextWriter provided by the caller.
+ /// </summary>
+ /// <param name="writer"></param>
+ public InternalTraceWriter(TextWriter writer)
+ {
+ this.writer = writer;
+ }
+
+ /// <summary>
+ /// Returns the character encoding in which the output is written.
+ /// </summary>
+ /// <returns>The character encoding in which the output is written.</returns>
+ public override System.Text.Encoding Encoding
+ {
+ get { return writer.Encoding; }
+ }
+
+ /// <summary>
+ /// Writes a character to the text string or stream.
+ /// </summary>
+ /// <param name="value">The character to write to the text stream.</param>
+ public override void Write(char value)
+ {
+ lock (myLock)
+ {
+ writer.Write(value);
+ }
+ }
+
+ /// <summary>
+ /// Writes a string to the text string or stream.
+ /// </summary>
+ /// <param name="value">The string to write.</param>
+ public override void Write(string value)
+ {
+ lock (myLock)
+ {
+ base.Write(value);
+ }
+ }
+
+ /// <summary>
+ /// Writes a string followed by a line terminator to the text string or stream.
+ /// </summary>
+ /// <param name="value">The string to write. If <paramref name="value" /> is null, only the line terminator is written.</param>
+ public override void WriteLine(string value)
+ {
+ writer.WriteLine(value);
+ }
+
+ /// <summary>
+ /// Releases the unmanaged resources used by the <see cref="T:System.IO.TextWriter" /> and optionally releases the managed resources.
+ /// </summary>
+ /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && writer != null)
+ {
+ writer.Flush();
+ writer.Dispose();
+ writer = null;
+ }
+
+ base.Dispose(disposing);
+ }
+
+ /// <summary>
+ /// Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.
+ /// </summary>
+ public override void Flush()
+ {
+ if ( writer != null )
+ writer.Flush();
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2013 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.IO;
+
+#if NUNIT_ENGINE
+namespace NUnit.Engine.Internal
+#elif NUNIT_FRAMEWORK
+namespace NUnit.Framework.Internal
+#else
+namespace NUnit.Common
+#endif
+{
+ /// <summary>
+ /// Provides internal logging to the NUnit framework
+ /// </summary>
+ public class Logger : ILogger
+ {
+ private readonly static string TIME_FMT = "HH:mm:ss.fff";
+ private readonly static string TRACE_FMT = "{0} {1,-5} [{2,2}] {3}: {4}";
+
+ private string name;
+ private string fullname;
+ private InternalTraceLevel maxLevel;
+ private TextWriter writer;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Logger"/> class.
+ /// </summary>
+ /// <param name="name">The name.</param>
+ /// <param name="level">The log level.</param>
+ /// <param name="writer">The writer where logs are sent.</param>
+ public Logger(string name, InternalTraceLevel level, TextWriter writer)
+ {
+ this.maxLevel = level;
+ this.writer = writer;
+ this.fullname = this.name = name;
+ int index = fullname.LastIndexOf('.');
+ if (index >= 0)
+ this.name = fullname.Substring(index + 1);
+ }
+
+ #region Error
+ /// <summary>
+ /// Logs the message at error level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ public void Error(string message)
+ {
+ Log(InternalTraceLevel.Error, message);
+ }
+
+ /// <summary>
+ /// Logs the message at error level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="args">The message arguments.</param>
+ public void Error(string message, params object[] args)
+ {
+ Log(InternalTraceLevel.Error, message, args);
+ }
+
+ //public void Error(string message, Exception ex)
+ //{
+ // if (service.Level >= InternalTraceLevel.Error)
+ // {
+ // service.Log(InternalTraceLevel.Error, message, name, ex);
+ // }
+ //}
+ #endregion
+
+ #region Warning
+ /// <summary>
+ /// Logs the message at warm level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ public void Warning(string message)
+ {
+ Log(InternalTraceLevel.Warning, message);
+ }
+
+ /// <summary>
+ /// Logs the message at warning level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="args">The message arguments.</param>
+ public void Warning(string message, params object[] args)
+ {
+ Log(InternalTraceLevel.Warning, message, args);
+ }
+ #endregion
+
+ #region Info
+ /// <summary>
+ /// Logs the message at info level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ public void Info(string message)
+ {
+ Log(InternalTraceLevel.Info, message);
+ }
+
+ /// <summary>
+ /// Logs the message at info level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="args">The message arguments.</param>
+ public void Info(string message, params object[] args)
+ {
+ Log(InternalTraceLevel.Info, message, args);
+ }
+ #endregion
+
+ #region Debug
+ /// <summary>
+ /// Logs the message at debug level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ public void Debug(string message)
+ {
+ Log(InternalTraceLevel.Verbose, message);
+ }
+
+ /// <summary>
+ /// Logs the message at debug level.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="args">The message arguments.</param>
+ public void Debug(string message, params object[] args)
+ {
+ Log(InternalTraceLevel.Verbose, message, args);
+ }
+ #endregion
+
+ #region Helper Methods
+ private void Log(InternalTraceLevel level, string message)
+ {
+ if (writer != null && this.maxLevel >= level)
+ WriteLog(level, message);
+ }
+
+ private void Log(InternalTraceLevel level, string format, params object[] args)
+ {
+ if (this.maxLevel >= level)
+ WriteLog(level, string.Format( format, args ) );
+ }
+
+ private void WriteLog(InternalTraceLevel level, string message)
+ {
+ writer.WriteLine(TRACE_FMT,
+ DateTime.Now.ToString(TIME_FMT),
+ level == InternalTraceLevel.Verbose ? "Debug" : level.ToString(),
+#if PORTABLE
+ System.Environment.CurrentManagedThreadId,
+#else
+ System.Threading.Thread.CurrentThread.ManagedThreadId,
+#endif
+ name,
+ message);
+ }
+
+#endregion
+ }
+}
--- /dev/null
+//
+// Options.cs
+//
+// Authors:
+// Jonathan Pryor <jpryor@novell.com>
+//
+// Copyright (C) 2008 Novell (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+// Compile With:
+// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
+// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
+//
+// The LINQ version just changes the implementation of
+// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
+
+//
+// A Getopt::Long-inspired option parsing library for C#.
+//
+// NDesk.Options.OptionSet is built upon a key/value table, where the
+// key is a option format string and the value is a delegate that is
+// invoked when the format string is matched.
+//
+// Option format strings:
+// Regex-like BNF Grammar:
+// name: .+
+// type: [=:]
+// sep: ( [^{}]+ | '{' .+ '}' )?
+// aliases: ( name type sep ) ( '|' name type sep )*
+//
+// Each '|'-delimited name is an alias for the associated action. If the
+// format string ends in a '=', it has a required value. If the format
+// string ends in a ':', it has an optional value. If neither '=' or ':'
+// is present, no value is supported. `=' or `:' need only be defined on one
+// alias, but if they are provided on more than one they must be consistent.
+//
+// Each alias portion may also end with a "key/value separator", which is used
+// to split option values if the option accepts > 1 value. If not specified,
+// it defaults to '=' and ':'. If specified, it can be any character except
+// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
+// used (i.e. the separate values should be distinct arguments), then "{}"
+// should be used as the separator.
+//
+// Options are extracted either from the current option by looking for
+// the option name followed by an '=' or ':', or is taken from the
+// following option IFF:
+// - The current option does not contain a '=' or a ':'
+// - The current option requires a value (i.e. not a Option type of ':')
+//
+// The `name' used in the option format string does NOT include any leading
+// option indicator, such as '-', '--', or '/'. All three of these are
+// permitted/required on any named option.
+//
+// Option bundling is permitted so long as:
+// - '-' is used to start the option group
+// - all of the bundled options are a single character
+// - at most one of the bundled options accepts a value, and the value
+// provided starts from the next character to the end of the string.
+//
+// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
+// as '-Dname=value'.
+//
+// Option processing is disabled by specifying "--". All options after "--"
+// are returned by OptionSet.Parse() unchanged and unprocessed.
+//
+// Unprocessed options are returned from OptionSet.Parse().
+//
+// Examples:
+// int verbose = 0;
+// OptionSet p = new OptionSet ()
+// .Add ("v", v => ++verbose)
+// .Add ("name=|value=", v => Console.WriteLine (v));
+// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
+//
+// The above would parse the argument string array, and would invoke the
+// lambda expression three times, setting `verbose' to 3 when complete.
+// It would also print out "A" and "B" to standard output.
+// The returned array would contain the string "extra".
+//
+// C# 3.0 collection initializers are supported and encouraged:
+// var p = new OptionSet () {
+// { "h|?|help", v => ShowHelp () },
+// };
+//
+// System.ComponentModel.TypeConverter is also supported, allowing the use of
+// custom data types in the callback type; TypeConverter.ConvertFromString()
+// is used to convert the value option to an instance of the specified
+// type:
+//
+// var p = new OptionSet () {
+// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
+// };
+//
+// Random other tidbits:
+// - Boolean options (those w/o '=' or ':' in the option format string)
+// are explicitly enabled if they are followed with '+', and explicitly
+// disabled if they are followed with '-':
+// string a = null;
+// var p = new OptionSet () {
+// { "a", s => a = s },
+// };
+// p.Parse (new string[]{"-a"}); // sets v != null
+// p.Parse (new string[]{"-a+"}); // sets v != null
+// p.Parse (new string[]{"-a-"}); // sets v == null
+//
+// The NUnit version of this file introduces conditional compilation for
+// building under the Compact Framework (NETCF) and Silverlight (SILVERLIGHT)
+// as well as for use with a portable class library (PORTABLE).
+//
+// 11/5/2015 -
+// Change namespace to avoid conflict with user code use of mono.options
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Globalization;
+using System.IO;
+using System.Reflection;
+//using System.Runtime.Serialization;
+using System.Text;
+using System.Text.RegularExpressions;
+
+// Missing XML Docs
+#pragma warning disable 1591
+
+#if PORTABLE
+using NUnit.Compatibility;
+#else
+using System.Security.Permissions;
+#endif
+
+#if LINQ
+using System.Linq;
+#endif
+
+#if TEST
+using NDesk.Options;
+#endif
+
+#if NUNIT_CONSOLE || NUNITLITE || NUNIT_ENGINE
+namespace NUnit.Options
+#elif NDESK_OPTIONS
+namespace NDesk.Options
+#else
+namespace Mono.Options
+#endif
+{
+ public class OptionValueCollection : IList, IList<string> {
+
+ List<string> values = new List<string> ();
+ OptionContext c;
+
+ internal OptionValueCollection (OptionContext c)
+ {
+ this.c = c;
+ }
+
+ #region ICollection
+ void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
+ bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
+ object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
+ #endregion
+
+ #region ICollection<T>
+ public void Add (string item) {values.Add (item);}
+ public void Clear () {values.Clear ();}
+ public bool Contains (string item) {return values.Contains (item);}
+ public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
+ public bool Remove (string item) {return values.Remove (item);}
+ public int Count {get {return values.Count;}}
+ public bool IsReadOnly {get {return false;}}
+ #endregion
+
+ #region IEnumerable
+ IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
+ #endregion
+
+ #region IEnumerable<T>
+ public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
+ #endregion
+
+ #region IList
+ int IList.Add (object value) {return (values as IList).Add (value);}
+ bool IList.Contains (object value) {return (values as IList).Contains (value);}
+ int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
+ void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
+ void IList.Remove (object value) {(values as IList).Remove (value);}
+ void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
+ bool IList.IsFixedSize {get {return false;}}
+ object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
+ #endregion
+
+ #region IList<T>
+ public int IndexOf (string item) {return values.IndexOf (item);}
+ public void Insert (int index, string item) {values.Insert (index, item);}
+ public void RemoveAt (int index) {values.RemoveAt (index);}
+
+ private void AssertValid (int index)
+ {
+ if (c.Option == null)
+ throw new InvalidOperationException ("OptionContext.Option is null.");
+ if (index >= c.Option.MaxValueCount)
+ throw new ArgumentOutOfRangeException ("index");
+ if (c.Option.OptionValueType == OptionValueType.Required &&
+ index >= values.Count)
+ throw new OptionException (string.Format (
+ c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
+ c.OptionName);
+ }
+
+ public string this [int index] {
+ get {
+ AssertValid (index);
+ return index >= values.Count ? null : values [index];
+ }
+ set {
+ values [index] = value;
+ }
+ }
+ #endregion
+
+ public List<string> ToList ()
+ {
+ return new List<string> (values);
+ }
+
+ public string[] ToArray ()
+ {
+ return values.ToArray ();
+ }
+
+ public override string ToString ()
+ {
+ return string.Join (", ", values.ToArray ());
+ }
+ }
+
+ public class OptionContext {
+ private Option option;
+ private string name;
+ private int index;
+ private OptionSet set;
+ private OptionValueCollection c;
+
+ public OptionContext (OptionSet set)
+ {
+ this.set = set;
+ this.c = new OptionValueCollection (this);
+ }
+
+ public Option Option {
+ get {return option;}
+ set {option = value;}
+ }
+
+ public string OptionName {
+ get {return name;}
+ set {name = value;}
+ }
+
+ public int OptionIndex {
+ get {return index;}
+ set {index = value;}
+ }
+
+ public OptionSet OptionSet {
+ get {return set;}
+ }
+
+ public OptionValueCollection OptionValues {
+ get {return c;}
+ }
+ }
+
+ public enum OptionValueType {
+ None,
+ Optional,
+ Required,
+ }
+
+ public abstract class Option {
+ string prototype, description;
+ string[] names;
+ OptionValueType type;
+ int count;
+ string[] separators;
+
+ protected Option (string prototype, string description)
+ : this (prototype, description, 1)
+ {
+ }
+
+ protected Option (string prototype, string description, int maxValueCount)
+ {
+ if (prototype == null)
+ throw new ArgumentNullException ("prototype");
+ if (prototype.Length == 0)
+ throw new ArgumentException ("Cannot be the empty string.", "prototype");
+ if (maxValueCount < 0)
+ throw new ArgumentOutOfRangeException ("maxValueCount");
+
+ this.prototype = prototype;
+ this.names = prototype.Split ('|');
+ this.description = description;
+ this.count = maxValueCount;
+ this.type = ParsePrototype ();
+
+ if (this.count == 0 && type != OptionValueType.None)
+ throw new ArgumentException (
+ "Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
+ "OptionValueType.Optional.",
+ "maxValueCount");
+ if (this.type == OptionValueType.None && maxValueCount > 1)
+ throw new ArgumentException (
+ string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
+ "maxValueCount");
+ if (Array.IndexOf (names, "<>") >= 0 &&
+ ((names.Length == 1 && this.type != OptionValueType.None) ||
+ (names.Length > 1 && this.MaxValueCount > 1)))
+ throw new ArgumentException (
+ "The default option handler '<>' cannot require values.",
+ "prototype");
+ }
+
+ public string Prototype {get {return prototype;}}
+ public string Description {get {return description;}}
+ public OptionValueType OptionValueType {get {return type;}}
+ public int MaxValueCount {get {return count;}}
+
+ public string[] GetNames ()
+ {
+ return (string[]) names.Clone ();
+ }
+
+ public string[] GetValueSeparators ()
+ {
+ if (separators == null)
+ return new string [0];
+ return (string[]) separators.Clone ();
+ }
+
+ protected static T Parse<T> (string value, OptionContext c)
+ {
+ Type tt = typeof (T);
+#if PORTABLE
+ bool nullable = tt.GetTypeInfo().IsValueType && tt.GetTypeInfo().IsGenericType &&
+ !tt.GetTypeInfo().IsGenericTypeDefinition &&
+ tt.GetGenericTypeDefinition () == typeof (Nullable<>);
+ Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
+#else
+ bool nullable = tt.IsValueType && tt.IsGenericType &&
+ !tt.IsGenericTypeDefinition &&
+ tt.GetGenericTypeDefinition () == typeof (Nullable<>);
+ Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
+#endif
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ TypeConverter conv = TypeDescriptor.GetConverter (targetType);
+#endif
+ T t = default (T);
+ try {
+ if (value != null)
+#if NETCF || SILVERLIGHT || PORTABLE
+ t = (T)Convert.ChangeType(value, tt, CultureInfo.InvariantCulture);
+#else
+ t = (T) conv.ConvertFromString (value);
+#endif
+ }
+ catch (Exception e) {
+ throw new OptionException (
+ string.Format (
+ c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
+ value, targetType.Name, c.OptionName),
+ c.OptionName, e);
+ }
+ return t;
+ }
+
+ internal string[] Names {get {return names;}}
+ internal string[] ValueSeparators {get {return separators;}}
+
+ static readonly char[] NameTerminator = new char[]{'=', ':'};
+
+ private OptionValueType ParsePrototype ()
+ {
+ char type = '\0';
+ List<string> seps = new List<string> ();
+ for (int i = 0; i < names.Length; ++i) {
+ string name = names [i];
+ if (name.Length == 0)
+ throw new ArgumentException ("Empty option names are not supported.", "prototype");
+
+ int end = name.IndexOfAny (NameTerminator);
+ if (end == -1)
+ continue;
+ names [i] = name.Substring (0, end);
+ if (type == '\0' || type == name [end])
+ type = name [end];
+ else
+ throw new ArgumentException (
+ string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
+ "prototype");
+ AddSeparators (name, end, seps);
+ }
+
+ if (type == '\0')
+ return OptionValueType.None;
+
+ if (count <= 1 && seps.Count != 0)
+ throw new ArgumentException (
+ string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
+ "prototype");
+ if (count > 1) {
+ if (seps.Count == 0)
+ this.separators = new string[]{":", "="};
+ else if (seps.Count == 1 && seps [0].Length == 0)
+ this.separators = null;
+ else
+ this.separators = seps.ToArray ();
+ }
+
+ return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
+ }
+
+ private static void AddSeparators (string name, int end, ICollection<string> seps)
+ {
+ int start = -1;
+ for (int i = end+1; i < name.Length; ++i) {
+ switch (name [i]) {
+ case '{':
+ if (start != -1)
+ throw new ArgumentException (
+ string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
+ "prototype");
+ start = i+1;
+ break;
+ case '}':
+ if (start == -1)
+ throw new ArgumentException (
+ string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
+ "prototype");
+ seps.Add (name.Substring (start, i-start));
+ start = -1;
+ break;
+ default:
+ if (start == -1)
+ seps.Add (name [i].ToString ());
+ break;
+ }
+ }
+ if (start != -1)
+ throw new ArgumentException (
+ string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
+ "prototype");
+ }
+
+ public void Invoke (OptionContext c)
+ {
+ OnParseComplete (c);
+ c.OptionName = null;
+ c.Option = null;
+ c.OptionValues.Clear ();
+ }
+
+ protected abstract void OnParseComplete (OptionContext c);
+
+ public override string ToString ()
+ {
+ return Prototype;
+ }
+ }
+
+#if !PORTABLE
+ [Serializable]
+#endif
+ public class OptionException : Exception
+ {
+ private string option;
+
+ public OptionException ()
+ {
+ }
+
+ public OptionException (string message, string optionName)
+ : base (message)
+ {
+ this.option = optionName;
+ }
+
+ public OptionException (string message, string optionName, Exception innerException)
+ : base (message, innerException)
+ {
+ this.option = optionName;
+ }
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ protected OptionException (SerializationInfo info, StreamingContext context)
+ : base (info, context)
+ {
+ this.option = info.GetString ("OptionName");
+ }
+#endif
+
+ public string OptionName {
+ get {return this.option;}
+ }
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
+ public override void GetObjectData (SerializationInfo info, StreamingContext context)
+ {
+ base.GetObjectData (info, context);
+ info.AddValue ("OptionName", option);
+ }
+#endif
+ }
+
+ public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
+
+ public class OptionSet : KeyedCollection<string, Option>
+ {
+#if !PORTABLE
+ public OptionSet ()
+ : this (delegate (string f) {return f;})
+ {
+ }
+
+ public OptionSet (Converter<string, string> localizer)
+ {
+ this.localizer = localizer;
+ }
+
+ Converter<string, string> localizer;
+
+ public Converter<string, string> MessageLocalizer {
+ get {return localizer;}
+ }
+#else
+ string localizer(string msg)
+ {
+ return msg;
+ }
+
+ public string MessageLocalizer(string msg)
+ {
+ return msg;
+ }
+#endif
+
+ protected override string GetKeyForItem (Option item)
+ {
+ if (item == null)
+ throw new ArgumentNullException ("option");
+ if (item.Names != null && item.Names.Length > 0)
+ return item.Names [0];
+ // This should never happen, as it's invalid for Option to be
+ // constructed w/o any names.
+ throw new InvalidOperationException ("Option has no names!");
+ }
+
+ [Obsolete ("Use KeyedCollection.this[string]")]
+ protected Option GetOptionForName (string option)
+ {
+ if (option == null)
+ throw new ArgumentNullException ("option");
+ try {
+ return base [option];
+ }
+ catch (KeyNotFoundException) {
+ return null;
+ }
+ }
+
+ protected override void InsertItem (int index, Option item)
+ {
+ base.InsertItem (index, item);
+ AddImpl (item);
+ }
+
+ protected override void RemoveItem (int index)
+ {
+ base.RemoveItem (index);
+ Option p = Items [index];
+ // KeyedCollection.RemoveItem() handles the 0th item
+ for (int i = 1; i < p.Names.Length; ++i) {
+ Dictionary.Remove (p.Names [i]);
+ }
+ }
+
+ protected override void SetItem (int index, Option item)
+ {
+ base.SetItem (index, item);
+ RemoveItem (index);
+ AddImpl (item);
+ }
+
+ private void AddImpl (Option option)
+ {
+ if (option == null)
+ throw new ArgumentNullException ("option");
+ List<string> added = new List<string> (option.Names.Length);
+ try {
+ // KeyedCollection.InsertItem/SetItem handle the 0th name.
+ for (int i = 1; i < option.Names.Length; ++i) {
+ Dictionary.Add (option.Names [i], option);
+ added.Add (option.Names [i]);
+ }
+ }
+ catch (Exception) {
+ foreach (string name in added)
+ Dictionary.Remove (name);
+ throw;
+ }
+ }
+
+ public new OptionSet Add (Option option)
+ {
+ base.Add (option);
+ return this;
+ }
+
+ sealed class ActionOption : Option {
+ Action<OptionValueCollection> action;
+
+ public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
+ : base (prototype, description, count)
+ {
+ if (action == null)
+ throw new ArgumentNullException ("action");
+ this.action = action;
+ }
+
+ protected override void OnParseComplete (OptionContext c)
+ {
+ action (c.OptionValues);
+ }
+ }
+
+ public OptionSet Add (string prototype, Action<string> action)
+ {
+ return Add (prototype, null, action);
+ }
+
+ public OptionSet Add (string prototype, string description, Action<string> action)
+ {
+ if (action == null)
+ throw new ArgumentNullException ("action");
+ Option p = new ActionOption (prototype, description, 1,
+ delegate (OptionValueCollection v) { action (v [0]); });
+ base.Add (p);
+ return this;
+ }
+
+ public OptionSet Add (string prototype, OptionAction<string, string> action)
+ {
+ return Add (prototype, null, action);
+ }
+
+ public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
+ {
+ if (action == null)
+ throw new ArgumentNullException ("action");
+ Option p = new ActionOption (prototype, description, 2,
+ delegate (OptionValueCollection v) {action (v [0], v [1]);});
+ base.Add (p);
+ return this;
+ }
+
+ sealed class ActionOption<T> : Option {
+ Action<T> action;
+
+ public ActionOption (string prototype, string description, Action<T> action)
+ : base (prototype, description, 1)
+ {
+ if (action == null)
+ throw new ArgumentNullException ("action");
+ this.action = action;
+ }
+
+ protected override void OnParseComplete (OptionContext c)
+ {
+ action (Parse<T> (c.OptionValues [0], c));
+ }
+ }
+
+ sealed class ActionOption<TKey, TValue> : Option {
+ OptionAction<TKey, TValue> action;
+
+ public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
+ : base (prototype, description, 2)
+ {
+ if (action == null)
+ throw new ArgumentNullException ("action");
+ this.action = action;
+ }
+
+ protected override void OnParseComplete (OptionContext c)
+ {
+ action (
+ Parse<TKey> (c.OptionValues [0], c),
+ Parse<TValue> (c.OptionValues [1], c));
+ }
+ }
+
+ public OptionSet Add<T> (string prototype, Action<T> action)
+ {
+ return Add (prototype, null, action);
+ }
+
+ public OptionSet Add<T> (string prototype, string description, Action<T> action)
+ {
+ return Add (new ActionOption<T> (prototype, description, action));
+ }
+
+ public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
+ {
+ return Add (prototype, null, action);
+ }
+
+ public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
+ {
+ return Add (new ActionOption<TKey, TValue> (prototype, description, action));
+ }
+
+ protected virtual OptionContext CreateOptionContext ()
+ {
+ return new OptionContext (this);
+ }
+
+#if LINQ
+ public List<string> Parse (IEnumerable<string> arguments)
+ {
+ bool process = true;
+ OptionContext c = CreateOptionContext ();
+ c.OptionIndex = -1;
+ var def = GetOptionForName ("<>");
+ var unprocessed =
+ from argument in arguments
+ where ++c.OptionIndex >= 0 && (process || def != null)
+ ? process
+ ? argument == "--"
+ ? (process = false)
+ : !Parse (argument, c)
+ ? def != null
+ ? Unprocessed (null, def, c, argument)
+ : true
+ : false
+ : def != null
+ ? Unprocessed (null, def, c, argument)
+ : true
+ : true
+ select argument;
+ List<string> r = unprocessed.ToList ();
+ if (c.Option != null)
+ c.Option.Invoke (c);
+ return r;
+ }
+#else
+ public List<string> Parse (IEnumerable<string> arguments)
+ {
+ OptionContext c = CreateOptionContext ();
+ c.OptionIndex = -1;
+ bool process = true;
+ List<string> unprocessed = new List<string> ();
+ Option def = Contains ("<>") ? this ["<>"] : null;
+ foreach (string argument in arguments) {
+ ++c.OptionIndex;
+ if (argument == "--") {
+ process = false;
+ continue;
+ }
+ if (!process) {
+ Unprocessed (unprocessed, def, c, argument);
+ continue;
+ }
+ if (!Parse (argument, c))
+ Unprocessed (unprocessed, def, c, argument);
+ }
+ if (c.Option != null)
+ c.Option.Invoke (c);
+ return unprocessed;
+ }
+#endif
+
+ private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
+ {
+ if (def == null) {
+ extra.Add (argument);
+ return false;
+ }
+ c.OptionValues.Add (argument);
+ c.Option = def;
+ c.Option.Invoke (c);
+ return false;
+ }
+
+ private readonly Regex ValueOption = new Regex (
+ @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
+
+ protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
+ {
+ if (argument == null)
+ throw new ArgumentNullException ("argument");
+
+ flag = name = sep = value = null;
+ Match m = ValueOption.Match (argument);
+ if (!m.Success) {
+ return false;
+ }
+ flag = m.Groups ["flag"].Value;
+ name = m.Groups ["name"].Value;
+ if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
+ sep = m.Groups ["sep"].Value;
+ value = m.Groups ["value"].Value;
+ }
+ return true;
+ }
+
+ protected virtual bool Parse (string argument, OptionContext c)
+ {
+ if (c.Option != null) {
+ ParseValue (argument, c);
+ return true;
+ }
+
+ string f, n, s, v;
+ if (!GetOptionParts (argument, out f, out n, out s, out v))
+ return false;
+
+ Option p;
+ if (Contains (n)) {
+ p = this [n];
+ c.OptionName = f + n;
+ c.Option = p;
+ switch (p.OptionValueType) {
+ case OptionValueType.None:
+ c.OptionValues.Add (n);
+ c.Option.Invoke (c);
+ break;
+ case OptionValueType.Optional:
+ case OptionValueType.Required:
+ ParseValue (v, c);
+ break;
+ }
+ return true;
+ }
+ // no match; is it a bool option?
+ if (ParseBool (argument, n, c))
+ return true;
+ // is it a bundled option?
+ if (ParseBundledValue (f, string.Concat (n + s + v), c))
+ return true;
+
+ return false;
+ }
+
+ private void ParseValue (string option, OptionContext c)
+ {
+ if (option != null)
+ foreach (string o in c.Option.ValueSeparators != null
+ ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None)
+ : new string[]{option}) {
+ c.OptionValues.Add (o);
+ }
+ if (c.OptionValues.Count == c.Option.MaxValueCount ||
+ c.Option.OptionValueType == OptionValueType.Optional)
+ c.Option.Invoke (c);
+ else if (c.OptionValues.Count > c.Option.MaxValueCount) {
+ throw new OptionException (localizer (string.Format (
+ "Error: Found {0} option values when expecting {1}.",
+ c.OptionValues.Count, c.Option.MaxValueCount)),
+ c.OptionName);
+ }
+ }
+
+ private bool ParseBool (string option, string n, OptionContext c)
+ {
+ Option p;
+ string rn;
+ if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
+ Contains ((rn = n.Substring (0, n.Length-1)))) {
+ p = this [rn];
+ string v = n [n.Length-1] == '+' ? option : null;
+ c.OptionName = option;
+ c.Option = p;
+ c.OptionValues.Add (v);
+ p.Invoke (c);
+ return true;
+ }
+ return false;
+ }
+
+ private bool ParseBundledValue (string f, string n, OptionContext c)
+ {
+ if (f != "-")
+ return false;
+ for (int i = 0; i < n.Length; ++i) {
+ Option p;
+ string opt = f + n [i].ToString ();
+ string rn = n [i].ToString ();
+ if (!Contains (rn)) {
+ if (i == 0)
+ return false;
+ throw new OptionException (string.Format (localizer (
+ "Cannot bundle unregistered option '{0}'."), opt), opt);
+ }
+ p = this [rn];
+ switch (p.OptionValueType) {
+ case OptionValueType.None:
+ Invoke (c, opt, n, p);
+ break;
+ case OptionValueType.Optional:
+ case OptionValueType.Required: {
+ string v = n.Substring (i+1);
+ c.Option = p;
+ c.OptionName = opt;
+ ParseValue (v.Length != 0 ? v : null, c);
+ return true;
+ }
+ default:
+ throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
+ }
+ }
+ return true;
+ }
+
+ private static void Invoke (OptionContext c, string name, string value, Option option)
+ {
+ c.OptionName = name;
+ c.Option = option;
+ c.OptionValues.Add (value);
+ option.Invoke (c);
+ }
+
+ private const int OptionWidth = 29;
+
+ public void WriteOptionDescriptions (TextWriter o)
+ {
+ foreach (Option p in this) {
+ int written = 0;
+ if (!WriteOptionPrototype (o, p, ref written))
+ continue;
+
+ if (written < OptionWidth)
+ o.Write (new string (' ', OptionWidth - written));
+ else {
+ o.WriteLine ();
+ o.Write (new string (' ', OptionWidth));
+ }
+
+ bool indent = false;
+ string prefix = new string (' ', OptionWidth+2);
+ foreach (string line in GetLines (localizer (GetDescription (p.Description)))) {
+ if (indent)
+ o.Write (prefix);
+ o.WriteLine (line);
+ indent = true;
+ }
+ }
+ }
+
+ bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
+ {
+ string[] names = p.Names;
+
+ int i = GetNextOptionIndex (names, 0);
+ if (i == names.Length)
+ return false;
+
+ if (names [i].Length == 1) {
+ Write (o, ref written, " -");
+ Write (o, ref written, names [0]);
+ }
+ else {
+ Write (o, ref written, " --");
+ Write (o, ref written, names [0]);
+ }
+
+ for ( i = GetNextOptionIndex (names, i+1);
+ i < names.Length; i = GetNextOptionIndex (names, i+1)) {
+ Write (o, ref written, ", ");
+ Write (o, ref written, names [i].Length == 1 ? "-" : "--");
+ Write (o, ref written, names [i]);
+ }
+
+ if (p.OptionValueType == OptionValueType.Optional ||
+ p.OptionValueType == OptionValueType.Required) {
+ if (p.OptionValueType == OptionValueType.Optional) {
+ Write (o, ref written, localizer ("["));
+ }
+ Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
+ string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
+ ? p.ValueSeparators [0]
+ : " ";
+ for (int c = 1; c < p.MaxValueCount; ++c) {
+ Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
+ }
+ if (p.OptionValueType == OptionValueType.Optional) {
+ Write (o, ref written, localizer ("]"));
+ }
+ }
+ return true;
+ }
+
+ static int GetNextOptionIndex (string[] names, int i)
+ {
+ while (i < names.Length && names [i] == "<>") {
+ ++i;
+ }
+ return i;
+ }
+
+ static void Write (TextWriter o, ref int n, string s)
+ {
+ n += s.Length;
+ o.Write (s);
+ }
+
+ private static string GetArgumentName (int index, int maxIndex, string description)
+ {
+ if (description == null)
+ return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
+ string[] nameStart;
+ if (maxIndex == 1)
+ nameStart = new string[]{"{0:", "{"};
+ else
+ nameStart = new string[]{"{" + index + ":"};
+ for (int i = 0; i < nameStart.Length; ++i) {
+ int start, j = 0;
+ do {
+ start = description.IndexOf (nameStart [i], j);
+ } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
+ if (start == -1)
+ continue;
+ int end = description.IndexOf ("}", start);
+ if (end == -1)
+ continue;
+ return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
+ }
+ return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
+ }
+
+ private static string GetDescription (string description)
+ {
+ if (description == null)
+ return string.Empty;
+ StringBuilder sb = new StringBuilder (description.Length);
+ int start = -1;
+ for (int i = 0; i < description.Length; ++i) {
+ switch (description [i]) {
+ case '{':
+ if (i == start) {
+ sb.Append ('{');
+ start = -1;
+ }
+ else if (start < 0)
+ start = i + 1;
+ break;
+ case '}':
+ if (start < 0) {
+ if ((i+1) == description.Length || description [i+1] != '}')
+ throw new InvalidOperationException ("Invalid option description: " + description);
+ ++i;
+ sb.Append ("}");
+ }
+ else {
+ sb.Append (description.Substring (start, i - start));
+ start = -1;
+ }
+ break;
+ case ':':
+ if (start < 0)
+ goto default;
+ start = i + 1;
+ break;
+ default:
+ if (start < 0)
+ sb.Append (description [i]);
+ break;
+ }
+ }
+ return sb.ToString ();
+ }
+
+ private static IEnumerable<string> GetLines (string description)
+ {
+ if (string.IsNullOrEmpty (description)) {
+ yield return string.Empty;
+ yield break;
+ }
+ int length = 80 - OptionWidth - 1;
+ int start = 0, end;
+ do {
+ end = GetLineEnd (start, length, description);
+ char c = description [end-1];
+ if (char.IsWhiteSpace (c))
+ --end;
+ bool writeContinuation = end != description.Length && !IsEolChar (c);
+ string line = description.Substring (start, end - start) +
+ (writeContinuation ? "-" : "");
+ yield return line;
+ start = end;
+ if (char.IsWhiteSpace (c))
+ ++start;
+ length = 80 - OptionWidth - 2 - 1;
+ } while (end < description.Length);
+ }
+
+ private static bool IsEolChar (char c)
+ {
+ return !char.IsLetterOrDigit (c);
+ }
+
+ private static int GetLineEnd (int start, int length, string description)
+ {
+ int end = System.Math.Min (start + length, description.Length);
+ int sep = -1;
+ for (int i = start+1; i < end; ++i) {
+ if (description [i] == '\n')
+ return i+1;
+ if (IsEolChar (description [i]))
+ sep = i+1;
+ }
+ if (sep == -1 || end == description.Length)
+ return end;
+ return sep;
+ }
+ }
+}
+
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Common
+{
+ /// <summary>
+ /// OutputSpecification encapsulates a file output path and format
+ /// for use in saving the results of a run.
+ /// </summary>
+ public class OutputSpecification
+ {
+ #region Constructor
+
+ /// <summary>
+ /// Construct an OutputSpecification from an option value.
+ /// </summary>
+ /// <param name="spec">The option value string.</param>
+ public OutputSpecification(string spec)
+ {
+ if (spec == null)
+ throw new NullReferenceException("Output spec may not be null");
+
+ string[] parts = spec.Split(';');
+ this.OutputPath = parts[0];
+
+ for (int i = 1; i < parts.Length; i++)
+ {
+ string[] opt = parts[i].Split('=');
+
+ if (opt.Length != 2)
+ throw new ArgumentException();
+
+ switch (opt[0].Trim())
+ {
+ case "format":
+ string fmt = opt[1].Trim();
+
+ if (this.Format != null && this.Format != fmt)
+ throw new ArgumentException(
+ string.Format("Conflicting format options: {0}", spec));
+
+ this.Format = fmt;
+ break;
+
+ case "transform":
+ string val = opt[1].Trim();
+
+ if (this.Transform != null && this.Transform != val)
+ throw new ArgumentException(
+ string.Format("Conflicting transform options: {0}", spec));
+
+ if (this.Format != null && this.Format != "user")
+ throw new ArgumentException(
+ string.Format("Conflicting format options: {0}", spec));
+
+ this.Format = "user";
+ this.Transform = opt[1].Trim();
+ break;
+ }
+ }
+
+ if (Format == null)
+ Format = "nunit3";
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Gets the path to which output will be written
+ /// </summary>
+ public string OutputPath { get; private set; }
+
+ /// <summary>
+ /// Gets the name of the format to be used
+ /// </summary>
+ public string Format { get; private set; }
+
+ /// <summary>
+ /// Gets the file name of a transform to be applied
+ /// </summary>
+ public string Transform { get; private set; }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Common
+{
+ /// <summary>
+ /// PackageSettings is a static class containing constant values that
+ /// are used as keys in setting up a TestPackage. These values are used in
+ /// the engine and framework. Setting values may be a string, int or bool.
+ /// </summary>
+ public static class PackageSettings
+ {
+ #region Common Settings - Used by both the Engine and the 3.0 Framework
+
+ /// <summary>
+ /// Flag (bool) indicating whether tests are being debugged.
+ /// </summary>
+ public const string DebugTests = "DebugTests";
+
+ /// <summary>
+ /// Flag (bool) indicating whether to pause execution of tests to allow
+ /// the user to attache a debugger.
+ /// </summary>
+ public const string PauseBeforeRun = "PauseBeforeRun";
+
+ /// <summary>
+ /// The InternalTraceLevel for this run. Values are: "Default",
+ /// "Off", "Error", "Warning", "Info", "Debug", "Verbose".
+ /// Default is "Off". "Debug" and "Verbose" are synonyms.
+ /// </summary>
+ public const string InternalTraceLevel = "InternalTraceLevel";
+
+ /// <summary>
+ /// Full path of the directory to be used for work and result files.
+ /// This path is provided to tests by the frameowrk TestContext.
+ /// </summary>
+ public const string WorkDirectory = "WorkDirectory";
+
+ #endregion
+
+ #region Engine Settings - Used by the Engine itself
+
+ /// <summary>
+ /// The name of the config to use in loading a project.
+ /// If not specified, the first config found is used.
+ /// </summary>
+ public const string ActiveConfig = "ActiveConfig";
+
+ /// <summary>
+ /// Bool indicating whether the engine should determine the private
+ /// bin path by examining the paths to all the tests. Defaults to
+ /// true unless PrivateBinPath is specified.
+ /// </summary>
+ public const string AutoBinPath = "AutoBinPath";
+
+ /// <summary>
+ /// The ApplicationBase to use in loading the tests. If not
+ /// specified, and each assembly has its own process, then the
+ /// location of the assembly is used. For multiple assemblies
+ /// in a single process, the closest common root directory is used.
+ /// </summary>
+ public const string BasePath = "BasePath";
+
+ /// <summary>
+ /// Path to the config file to use in running the tests.
+ /// </summary>
+ public const string ConfigurationFile = "ConfigurationFile";
+
+ /// <summary>
+ /// Bool flag indicating whether a debugger should be launched at agent
+ /// startup. Used only for debugging NUnit itself.
+ /// </summary>
+ public const string DebugAgent = "DebugAgent";
+
+ /// <summary>
+ /// Indicates how to load tests across AppDomains. Values are:
+ /// "Default", "None", "Single", "Multiple". Default is "Multiple"
+ /// if more than one assembly is loaded in a process. Otherwise,
+ /// it is "Single".
+ /// </summary>
+ public const string DomainUsage = "DomainUsage";
+
+ /// <summary>
+ /// The private binpath used to locate assemblies. Directory paths
+ /// is separated by a semicolon. It's an error to specify this and
+ /// also set AutoBinPath to true.
+ /// </summary>
+ public const string PrivateBinPath = "PrivateBinPath";
+
+ /// <summary>
+ /// The maximum number of test agents permitted to run simultneously.
+ /// Ignored if the ProcessModel is not set or defaulted to Multiple.
+ /// </summary>
+ public const string MaxAgents = "MaxAgents";
+
+ /// <summary>
+ /// Indicates how to allocate assemblies to processes. Values are:
+ /// "Default", "Single", "Separate", "Multiple". Default is "Multiple"
+ /// for more than one assembly, "Separate" for a single assembly.
+ /// </summary>
+ public const string ProcessModel = "ProcessModel";
+
+ /// <summary>
+ /// Indicates the desired runtime to use for the tests. Values
+ /// are strings like "net-4.5", "mono-4.0", etc. Default is to
+ /// use the target framework for which an assembly was built.
+ /// </summary>
+ public const string RuntimeFramework = "RuntimeFramework";
+
+ /// <summary>
+ /// Bool flag indicating that the test should be run in a 32-bit process
+ /// on a 64-bit system. By default, NUNit runs in a 64-bit process on
+ /// a 64-bit system. Ignored if set on a 32-bit system.
+ /// </summary>
+ public const string RunAsX86 = "RunAsX86";
+
+ /// <summary>
+ /// Indicates that test runners should be disposed after the tests are executed
+ /// </summary>
+ public const string DisposeRunners = "DisposeRunners";
+
+ /// <summary>
+ /// Bool flag indicating that the test assemblies should be shadow copied.
+ /// Defaults to false.
+ /// </summary>
+ public const string ShadowCopyFiles = "ShadowCopyFiles";
+
+ /// <summary>
+ /// Bool flag indicating that user profile should be loaded on test runner processes
+ /// </summary>
+ public const string LoadUserProfile = "LoadUserProfile";
+ #endregion
+
+ #region Framework Settings - Passed through and used by the 3.0 Framework
+
+ /// <summary>
+ /// Integer value in milliseconds for the default timeout value
+ /// for test cases. If not specified, there is no timeout except
+ /// as specified by attributes on the tests themselves.
+ /// </summary>
+ public const string DefaultTimeout = "DefaultTimeout";
+
+ /// <summary>
+ /// A TextWriter to which the internal trace will be sent.
+ /// </summary>
+ public const string InternalTraceWriter = "InternalTraceWriter";
+
+ /// <summary>
+ /// A list of tests to be loaded.
+ /// </summary>
+ // TODO: Remove?
+ public const string LOAD = "LOAD";
+
+ /// <summary>
+ /// The number of test threads to run for the assembly. If set to
+ /// 1, a single queue is used. If set to 0, tests are executed
+ /// directly, without queuing.
+ /// </summary>
+ public const string NumberOfTestWorkers = "NumberOfTestWorkers";
+
+ /// <summary>
+ /// The random seed to be used for this assembly. If specified
+ /// as the value reported from a prior run, the framework should
+ /// generate identical random values for tests as were used for
+ /// that run, provided that no change has been made to the test
+ /// assembly. Default is a random value itself.
+ /// </summary>
+ public const string RandomSeed = "RandomSeed";
+
+ /// <summary>
+ /// If true, execution stops after the first error or failure.
+ /// </summary>
+ public const string StopOnError = "StopOnError";
+
+ /// <summary>
+ /// If true, use of the event queue is suppressed and test events are synchronous.
+ /// </summary>
+ public const string SynchronousEvents = "SynchronousEvents";
+
+ /// <summary>
+ /// The default naming pattern used in generating test names
+ /// </summary>
+ public const string DefaultTestNamePattern = "DefaultTestNamePattern";
+
+ /// <summary>
+ /// Parameters to be passed on to the test
+ /// </summary>
+ public const string TestParameters = "TestParameters";
+
+ #endregion
+
+ #region Internal Settings - Used only within the engine
+
+ /// <summary>
+ /// If the package represents an assembly, then this is the CLR version
+ /// stored in the assembly image. If it represents a project or other
+ /// group of assemblies, it is the maximum version for all the assemblies.
+ /// </summary>
+ public const string ImageRuntimeVersion = "ImageRuntimeVersion";
+
+ /// <summary>
+ /// True if any assembly in the package requires running as a 32-bit
+ /// process when on a 64-bit system.
+ /// </summary>
+ public const string ImageRequiresX86 = "ImageRequiresX86";
+
+ /// <summary>
+ /// True if any assembly in the package requires a special assembly resolution hook
+ /// in the default AppDomain in order to find dependent assemblies.
+ /// </summary>
+ public const string ImageRequiresDefaultAppDomainAssemblyResolver = "ImageRequiresDefaultAppDomainAssemblyResolver";
+
+ /// <summary>
+ /// The FrameworkName specified on a TargetFrameworkAttribute for the assembly
+ /// </summary>
+ public const string ImageTargetFrameworkName = "ImageTargetFrameworkName";
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections.Generic;
+
+namespace NUnit.Common
+{
+ /// <summary>
+ /// TestNameParser is used to parse the arguments to the
+ /// -run option, separating testnames at the correct point.
+ /// </summary>
+ public class TestNameParser
+ {
+ /// <summary>
+ /// Parse the -run argument and return an array of argument
+ /// </summary>
+ /// <param name="argument">argument</param>
+ /// <returns></returns>
+ public static string[] Parse(string argument)
+ {
+ List<string> list = new List<string>();
+
+ int index = 0;
+ while (index < argument.Length)
+ {
+ string name = GetTestName(argument, ref index);
+ if (name != null && name != string.Empty)
+ list.Add(name);
+ }
+
+ return list.ToArray();
+ }
+
+ private static string GetTestName(string argument, ref int index)
+ {
+ int separator = GetSeparator(argument, index);
+ string result;
+
+ if (separator >= 0)
+ {
+ result = argument.Substring(index, separator - index).Trim();
+ index = separator + 1;
+ }
+ else
+ {
+ result = argument.Substring(index).Trim();
+ index = argument.Length;
+ }
+
+ return result;
+ }
+
+ private static int GetSeparator(string argument, int index)
+ {
+ int nest = 0;
+
+ while (index < argument.Length)
+ {
+ switch (argument[index])
+ {
+ case ',':
+ if (nest == 0)
+ return index;
+ break;
+
+ case '"':
+ while (++index < argument.Length && argument[index] != '"')
+ ;
+ break;
+
+ case '(':
+ case '<':
+ nest++;
+ break;
+
+ case ')':
+ case '>':
+ nest--;
+ break;
+ }
+
+ index++;
+ }
+
+ return -1;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+// Missing XML Docs
+#pragma warning disable 1591
+
+#if NUNIT_ENGINE
+namespace NUnit.Engine
+#else
+namespace NUnit.Common
+#endif
+{
+ public class TestSelectionParser
+ {
+ private Tokenizer _tokenizer;
+
+ private static readonly Token LPAREN = new Token(TokenKind.Symbol, "(");
+ private static readonly Token RPAREN = new Token(TokenKind.Symbol, ")");
+ private static readonly Token AND_OP1 = new Token(TokenKind.Symbol, "&");
+ private static readonly Token AND_OP2 = new Token(TokenKind.Symbol, "&&");
+ private static readonly Token AND_OP3 = new Token(TokenKind.Word, "and");
+ private static readonly Token AND_OP4 = new Token(TokenKind.Word, "AND");
+ private static readonly Token OR_OP1 = new Token(TokenKind.Symbol, "|");
+ private static readonly Token OR_OP2 = new Token(TokenKind.Symbol, "||");
+ private static readonly Token OR_OP3 = new Token(TokenKind.Word, "or");
+ private static readonly Token OR_OP4 = new Token(TokenKind.Word, "OR");
+ private static readonly Token NOT_OP = new Token(TokenKind.Symbol, "!");
+
+ private static readonly Token EQ_OP1 = new Token(TokenKind.Symbol, "=");
+ private static readonly Token EQ_OP2 = new Token(TokenKind.Symbol, "==");
+ private static readonly Token NE_OP = new Token(TokenKind.Symbol, "!=");
+ private static readonly Token MATCH_OP = new Token(TokenKind.Symbol, "=~");
+ private static readonly Token NOMATCH_OP = new Token(TokenKind.Symbol, "!~");
+
+ private static readonly Token[] AND_OPS = new Token[] { AND_OP1, AND_OP2, AND_OP3, AND_OP4 };
+ private static readonly Token[] OR_OPS = new Token[] { OR_OP1, OR_OP2, OR_OP3, OR_OP4 };
+ private static readonly Token[] EQ_OPS = new Token[] { EQ_OP1, EQ_OP2 };
+ private static readonly Token[] REL_OPS = new Token[] { EQ_OP1, EQ_OP2, NE_OP, MATCH_OP, NOMATCH_OP };
+
+ private static readonly Token EOF = new Token(TokenKind.Eof);
+
+ public string Parse(string input)
+ {
+ _tokenizer = new Tokenizer(input);
+
+ if (_tokenizer.LookAhead == EOF)
+ throw new TestSelectionParserException("No input provided for test selection.");
+
+ var result = ParseFilterExpression();
+
+ Expect(EOF);
+ return result;
+ }
+
+ /// <summary>
+ /// Parse a single term or an or expression, returning the xml
+ /// </summary>
+ /// <returns></returns>
+ public string ParseFilterExpression()
+ {
+ var terms = new List<string>();
+ terms.Add(ParseFilterTerm());
+
+ while (LookingAt(OR_OPS))
+ {
+ NextToken();
+ terms.Add(ParseFilterTerm());
+ }
+
+ if (terms.Count == 1)
+ return terms[0];
+
+ var sb = new StringBuilder("<or>");
+
+ foreach (string term in terms)
+ sb.Append(term);
+
+ sb.Append("</or>");
+
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// Parse a single element or an and expression and return the xml
+ /// </summary>
+ public string ParseFilterTerm()
+ {
+ var elements = new List<string>();
+ elements.Add(ParseFilterElement());
+
+ while (LookingAt(AND_OPS))
+ {
+ NextToken();
+ elements.Add(ParseFilterElement());
+ }
+
+ if (elements.Count == 1)
+ return elements[0];
+
+ var sb = new StringBuilder("<and>");
+
+ foreach (string element in elements)
+ sb.Append(element);
+
+ sb.Append("</and>");
+
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// Parse a single filter element such as a category expression
+ /// and return the xml representation of the filter.
+ /// </summary>
+ public string ParseFilterElement()
+ {
+ if (LookingAt(LPAREN, NOT_OP))
+ return ParseExpressionInParentheses();
+
+ Token lhs = Expect(TokenKind.Word);
+
+ switch (lhs.Text)
+ {
+ case "id":
+ case "cat":
+ case "method":
+ case "class":
+ case "name":
+ case "test":
+ Token op = lhs.Text == "id"
+ ? Expect(EQ_OPS)
+ : Expect(REL_OPS);
+ Token rhs = Expect(TokenKind.String, TokenKind.Word);
+ return EmitFilterElement(lhs, op, rhs);
+
+ default:
+ // Assume it's a property name
+ op = Expect(REL_OPS);
+ rhs = Expect(TokenKind.String, TokenKind.Word);
+ return EmitPropertyElement(lhs, op, rhs);
+ //throw InvalidTokenError(lhs);
+ }
+ }
+
+ private static string EmitFilterElement(Token lhs, Token op, Token rhs)
+ {
+ string fmt = null;
+
+ if (op == EQ_OP1 || op == EQ_OP2)
+ fmt = "<{0}>{1}</{0}>";
+ else if (op == NE_OP)
+ fmt = "<not><{0}>{1}</{0}></not>";
+ else if (op == MATCH_OP)
+ fmt = "<{0} re='1'>{1}</{0}>";
+ else if (op == NOMATCH_OP)
+ fmt = "<not><{0} re='1'>{1}</{0}></not>";
+ else
+ fmt = "<{0} op='" + op.Text + "'>{1}</{0}>";
+
+ return EmitElement(fmt, lhs, rhs);
+ }
+
+ private static string EmitPropertyElement(Token lhs, Token op, Token rhs)
+ {
+ string fmt = null;
+
+ if (op == EQ_OP1 || op == EQ_OP2)
+ fmt = "<prop name='{0}'>{1}</prop>";
+ else if (op == NE_OP)
+ fmt = "<not><prop name='{0}'>{1}</prop></not>";
+ else if (op == MATCH_OP)
+ fmt = "<prop name='{0}' re='1'>{1}</prop>";
+ else if (op == NOMATCH_OP)
+ fmt = "<not><prop name='{0}' re='1'>{1}</prop></not>";
+ else
+ fmt = "<prop name='{0}' op='" + op.Text + "'>{1}</prop>";
+
+ return EmitElement(fmt, lhs, rhs);
+ }
+
+ private static string EmitElement(string fmt, Token lhs, Token rhs)
+ {
+ return string.Format(fmt, lhs.Text, XmlEscape(rhs.Text));
+ }
+
+ private string ParseExpressionInParentheses()
+ {
+ Token op = Expect(LPAREN, NOT_OP);
+
+ if (op == NOT_OP) Expect(LPAREN);
+
+ string result = ParseFilterExpression();
+
+ Expect(RPAREN);
+
+ if (op == NOT_OP)
+ result = "<not>" + result + "</not>";
+
+ return result;
+ }
+
+ // Require a token of one or more kinds
+ private Token Expect(params TokenKind[] kinds)
+ {
+ Token token = NextToken();
+
+ foreach (TokenKind kind in kinds)
+ if (token.Kind == kind)
+ return token;
+
+ throw InvalidTokenError(token);
+ }
+
+ // Require a token from a list of tokens
+ private Token Expect(params Token[] valid)
+ {
+ Token token = NextToken();
+
+ foreach (Token item in valid)
+ if (token == item)
+ return token;
+
+ throw InvalidTokenError(token);
+ }
+
+ private Exception InvalidTokenError(Token token)
+ {
+ return new TestSelectionParserException(string.Format(
+ "Unexpected token '{0}' at position {1} in selection expression.", token.Text, token.Pos));
+ }
+
+ private Token LookAhead
+ {
+ get { return _tokenizer.LookAhead; }
+ }
+
+ private bool LookingAt(params Token[] tokens)
+ {
+ foreach (Token token in tokens)
+ if (LookAhead == token)
+ return true;
+
+ return false;
+ }
+
+ private Token NextToken()
+ {
+ return _tokenizer.NextToken();
+ }
+
+ private static string XmlEscape(string text)
+ {
+ return text
+ .Replace("&", "&")
+ .Replace("\"", """)
+ .Replace("<", "<")
+ .Replace(">", ">")
+ .Replace("'", "'");
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+//using System.Runtime.Serialization;
+
+#if NUNIT_ENGINE
+namespace NUnit.Engine
+#else
+namespace NUnit.Common
+#endif
+{
+ /// <summary>
+ /// TestSelectionParserException is thrown when an error
+ /// is found while parsing the selection expression.
+ /// </summary>
+#if !PORTABLE
+ [Serializable]
+#endif
+ public class TestSelectionParserException : Exception
+ {
+ /// <summary>
+ /// Construct with a message
+ /// </summary>
+ public TestSelectionParserException(string message) : base(message) { }
+
+ /// <summary>
+ /// Construct with a message and inner exception
+ /// </summary>
+ /// <param name="message"></param>
+ /// <param name="innerException"></param>
+ public TestSelectionParserException(string message, Exception innerException) : base(message, innerException) { }
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Serialization constructor
+ /// </summary>
+ public TestSelectionParserException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+#endif
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Text;
+
+// Missing XML Docs
+#pragma warning disable 1591
+
+#if NUNIT_ENGINE
+namespace NUnit.Engine
+#else
+namespace NUnit.Common
+#endif
+{
+ public enum TokenKind
+ {
+ Eof,
+ Word,
+ String,
+ Symbol
+ }
+
+ public class Token
+ {
+ public Token(TokenKind kind) : this(kind, string.Empty) { }
+
+ public Token(TokenKind kind, char ch) : this(kind, ch.ToString()) { }
+
+ public Token(TokenKind kind, string text)
+ {
+ Kind = kind;
+ Text = text;
+ }
+
+ public TokenKind Kind { get; private set; }
+
+ public string Text { get; private set; }
+
+ public int Pos { get; set; }
+
+ #region Equality Overrides
+
+ public override bool Equals(object obj)
+ {
+ return obj is Token && this == (Token)obj;
+ }
+
+ public override int GetHashCode()
+ {
+ return Text.GetHashCode();
+ }
+
+ public override string ToString()
+ {
+ return Text != null
+ ? Kind.ToString() + ":" + Text
+ : Kind.ToString();
+ }
+
+ public static bool operator ==(Token t1, Token t2)
+ {
+ bool t1Null = ReferenceEquals(t1, null);
+ bool t2Null = ReferenceEquals(t2, null);
+
+ if (t1Null && t2Null)
+ return true;
+
+ if (t1Null || t2Null)
+ return false;
+
+ return t1.Kind == t2.Kind && t1.Text == t2.Text;
+ }
+
+ public static bool operator !=(Token t1, Token t2)
+ {
+ return !(t1 == t2);
+ }
+
+ #endregion
+ }
+
+ /// <summary>
+ /// Tokenizer class performs lexical analysis for the TestSelectionParser.
+ /// It recognizes a very limited set of tokens: words, symbols and
+ /// quoted strings. This is sufficient for the simple DSL we use to
+ /// select which tests to run.
+ /// </summary>
+ public class Tokenizer
+ {
+ private string _input;
+ private int _index;
+
+ private const char EOF_CHAR = '\0';
+ private const string WORD_BREAK_CHARS = "=!()&|";
+ private readonly string[] DOUBLE_CHAR_SYMBOLS = new string[] { "==", "=~", "!=", "!~", "&&", "||" };
+
+ private Token _lookahead;
+
+ public Tokenizer(string input)
+ {
+ if (input == null)
+ throw new ArgumentNullException("input");
+
+ _input = input;
+ _index = 0;
+ }
+
+ public Token LookAhead
+ {
+ get
+ {
+ if (_lookahead == null)
+ _lookahead = GetNextToken();
+
+ return _lookahead;
+ }
+ }
+
+ public Token NextToken()
+ {
+ Token result = _lookahead ?? GetNextToken();
+ _lookahead = null;
+ return result;
+ }
+
+ private Token GetNextToken()
+ {
+ SkipBlanks();
+
+ var ch = NextChar;
+ int pos = _index;
+
+ switch (ch)
+ {
+ case EOF_CHAR:
+ return new Token(TokenKind.Eof) { Pos = pos };
+
+ // Single char symbols
+ case '(':
+ case ')':
+ GetChar();
+ return new Token(TokenKind.Symbol, ch) { Pos = pos };
+
+ // Possible double char symbols
+ case '&':
+ case '|':
+ case '=':
+ case '!':
+ GetChar();
+ foreach(string dbl in DOUBLE_CHAR_SYMBOLS)
+ if (ch == dbl[0] && NextChar == dbl[1])
+ {
+ GetChar();
+ return new Token(TokenKind.Symbol, dbl) { Pos = pos };
+ }
+
+ return new Token(TokenKind.Symbol, ch);
+
+ case '"':
+ case '\'':
+ case '/':
+ return GetString();
+
+ default:
+ return GetWord();
+ }
+ }
+
+ private bool IsWordChar(char c)
+ {
+ if (char.IsWhiteSpace(c) || c == EOF_CHAR)
+ return false;
+
+ return WORD_BREAK_CHARS.IndexOf(c) < 0;
+ }
+
+ private Token GetWord()
+ {
+ var sb = new StringBuilder();
+ int pos = _index;
+
+ while (IsWordChar(NextChar))
+ sb.Append(GetChar());
+
+ return new Token(TokenKind.Word, sb.ToString()) { Pos = pos };
+ }
+
+ private Token GetString()
+ {
+ var sb = new StringBuilder();
+ int pos = _index;
+
+ char quote = GetChar(); // Save the initial quote char
+
+ while (NextChar != EOF_CHAR)
+ {
+ var ch = GetChar();
+ if (ch == '\\')
+ ch = GetChar();
+ else if (ch == quote)
+ break;
+ sb.Append(ch);
+ }
+
+ return new Token(TokenKind.String, sb.ToString()) { Pos = pos };
+ }
+
+ /// <summary>
+ /// Get the next character in the input, consuming it.
+ /// </summary>
+ /// <returns>The next char</returns>
+ private char GetChar()
+ {
+ return _index < _input.Length ? _input[_index++] : EOF_CHAR;
+ }
+
+ /// <summary>
+ /// Peek ahead at the next character in input
+ /// </summary>
+ private char NextChar
+ {
+ get
+ {
+ return _index < _input.Length ? _input[_index] : EOF_CHAR;
+ }
+ }
+
+ private void SkipBlanks()
+ {
+ while (char.IsWhiteSpace(NextChar))
+ _index++;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+
+namespace NUnit.Compatibility
+{
+ /// <summary>
+ /// Provides a platform-independent methods for getting attributes
+ /// for use by AttributeConstraint and AttributeExistsConstraint.
+ /// </summary>
+ public static class AttributeHelper
+ {
+ /// <summary>
+ /// Gets the custom attributes from the given object.
+ /// </summary>
+ /// <remarks>Portable libraries do not have an ICustomAttributeProvider, so we need to cast to each of
+ /// it's direct subtypes and try to get attributes off those instead.</remarks>
+ /// <param name="actual">The actual.</param>
+ /// <param name="attributeType">Type of the attribute.</param>
+ /// <param name="inherit">if set to <c>true</c> [inherit].</param>
+ /// <returns>A list of the given attribute on the given object.</returns>
+ public static Attribute[] GetCustomAttributes(object actual, Type attributeType, bool inherit)
+ {
+#if !PORTABLE
+ var attrProvider = actual as ICustomAttributeProvider;
+ if (attrProvider == null)
+ throw new ArgumentException(string.Format("Actual value {0} does not implement ICustomAttributeProvider.", actual), "actual");
+
+ return (Attribute[])attrProvider.GetCustomAttributes(attributeType, inherit);
+#else
+ var member = actual as MemberInfo;
+ if (member != null)
+ {
+ return (Attribute[])member.GetCustomAttributes(attributeType, inherit);
+ }
+
+ var param = actual as ParameterInfo;
+ if (param != null)
+ {
+ return (Attribute[])param.GetCustomAttributes(attributeType, inherit);
+ }
+
+ var assembly = actual as Assembly;
+ if (assembly != null)
+ {
+ return (Attribute[])assembly.GetCustomAttributes();
+ }
+
+ throw new ArgumentException(string.Format("Actual value {0} must be a MemberInfo, ParameterInfo or Assembly.", actual), "actual");
+#endif
+ }
+
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Compatibility
+{
+ /// <summary>
+ /// A MarshalByRefObject that lives forever
+ /// </summary>
+#if PORTABLE || SILVERLIGHT || NETCF
+ public class LongLivedMarshalByRefObject
+ {
+ }
+#else
+ public class LongLivedMarshalByRefObject : MarshalByRefObject
+ {
+ /// <summary>
+ /// Obtains a lifetime service object to control the lifetime policy for this instance.
+ /// </summary>
+ public override object InitializeLifetimeService()
+ {
+ return null;
+ }
+ }
+#endif
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if PORTABLE
+namespace NUnit.Compatibility
+{
+ /// <summary>
+ /// Some path based methods that we need even in the Portable framework which
+ /// does not have the System.IO.Path class
+ /// </summary>
+ public static class Path
+ {
+ /// <summary>
+ /// Windows directory separator
+ /// </summary>
+ public static readonly char WindowsSeparatorChar = '\\';
+ /// <summary>
+ /// Alternate directory separator
+ /// </summary>
+ public static readonly char AltDirectorySeparatorChar = '/';
+ /// <summary>
+ /// A volume separator character.
+ /// </summary>
+ public static readonly char VolumeSeparatorChar = ':';
+
+ /// <summary>
+ /// Get the file name and extension of the specified path string.
+ /// </summary>
+ /// <param name="path">The path string from which to obtain the file name and extension.</param>
+ /// <returns>The filename as a <see cref="T:System.String"/>. If the last character of <paramref name="path"/> is a directory or volume separator character, this method returns <see cref="F:System.String.Empty"/>. If <paramref name="path"/> is null, this method returns null.</returns>
+ public static string GetFileName(string path)
+ {
+ if (path != null)
+ {
+ int length = path.Length;
+ for( int index = length - 1; index >= 0; index--)
+ {
+ char ch = path[index];
+ if (ch == Path.WindowsSeparatorChar || ch == Path.AltDirectorySeparatorChar || ch == Path.VolumeSeparatorChar)
+ return path.Substring(index + 1, length - index - 1);
+ }
+ }
+ return path;
+ }
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Linq;
+using System.Collections.Generic;
+using System.Text;
+using System.Threading;
+
+namespace NUnit.Compatibility
+{
+#if NETCF
+ /// <summary>
+ ///
+ /// </summary>
+ public class ReaderWriterLockSlim
+ {
+ private object _lockObject = new object();
+
+ /// <summary>
+ ///
+ /// </summary>
+ public void EnterReadLock()
+ {
+ Monitor.Enter (_lockObject);
+ }
+
+ /// <summary>
+ ///
+ /// </summary>
+ public void EnterWriteLock()
+ {
+ Monitor.Enter(_lockObject);
+ }
+
+ /// <summary>
+ ///
+ /// </summary>
+ public void ExitReadLock()
+ {
+ Monitor.Exit(_lockObject);
+ }
+
+ /// <summary>
+ ///
+ /// </summary>
+ public void ExitWriteLock()
+ {
+ Monitor.Exit(_lockObject);
+ }
+ }
+#endif
+
+#if NET_2_0
+ /// <summary>
+ ///
+ /// </summary>
+ public static class ReaderWriterLockExtensions
+ {
+ /// <summary>
+ ///
+ /// </summary>
+ /// <param name="rwLock"></param>
+ public static void EnterReadLock(this ReaderWriterLock rwLock)
+ {
+ rwLock.AcquireReaderLock(Timeout.Infinite);
+ }
+
+ /// <summary>
+ ///
+ /// </summary>
+ /// <param name="rwLock"></param>
+ public static void EnterWriteLock(this ReaderWriterLock rwLock)
+ {
+ rwLock.AcquireWriterLock(Timeout.Infinite);
+ }
+
+ /// <summary>
+ ///
+ /// </summary>
+ /// <param name="rwLock"></param>
+ public static void ExitReadLock(this ReaderWriterLock rwLock)
+ {
+ rwLock.ReleaseReaderLock();
+ }
+
+ /// <summary>
+ ///
+ /// </summary>
+ /// <param name="rwLock"></param>
+ public static void ExitWriteLock(this ReaderWriterLock rwLock)
+ {
+ rwLock.ReleaseWriterLock();
+ }
+ }
+#endif
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Linq;
+
+namespace NUnit.Compatibility
+{
+ /// <summary>
+ /// Type extensions that apply to all target frameworks
+ /// </summary>
+ public static class AdditionalTypeExtensions
+ {
+ /// <summary>
+ /// Determines if the given <see cref="Type"/> array is castable/matches the <see cref="ParameterInfo"/> array.
+ /// </summary>
+ /// <param name="pinfos"></param>
+ /// <param name="ptypes"></param>
+ /// <returns></returns>
+ public static bool ParametersMatch(this ParameterInfo[] pinfos, Type[] ptypes)
+ {
+ if (pinfos.Length != ptypes.Length)
+ return false;
+
+ for (int i = 0; i < pinfos.Length; i++)
+ {
+ if (!pinfos[i].ParameterType.IsCastableFrom(ptypes[i]))
+ return false;
+ }
+ return true;
+ }
+
+ // §6.1.2 (Implicit numeric conversions) of the specification
+ static Dictionary<Type, List<Type>> convertibleValueTypes = new Dictionary<Type, List<Type>>() {
+ { typeof(decimal), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char) } },
+ { typeof(double), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } },
+ { typeof(float), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } },
+ { typeof(ulong), new List<Type> { typeof(byte), typeof(ushort), typeof(uint), typeof(char) } },
+ { typeof(long), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(char) } },
+ { typeof(uint), new List<Type> { typeof(byte), typeof(ushort), typeof(char) } },
+ { typeof(int), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(char) } },
+ { typeof(ushort), new List<Type> { typeof(byte), typeof(char) } },
+ { typeof(short), new List<Type> { typeof(byte) } }
+ };
+
+ /// <summary>
+ /// Determines if one type can be implicitly converted from another
+ /// </summary>
+ /// <param name="to"></param>
+ /// <param name="from"></param>
+ /// <returns></returns>
+ public static bool IsCastableFrom(this Type to, Type from)
+ {
+ if (to.IsAssignableFrom(from))
+ return true;
+
+ // Look for the marker that indicates from was null
+ if (from == typeof(NUnitNullType) && (to.GetTypeInfo().IsClass || to.FullName.StartsWith("System.Nullable")))
+ return true;
+
+ if (convertibleValueTypes.ContainsKey(to) && convertibleValueTypes[to].Contains(from))
+ return true;
+
+ return from.GetMethods(BindingFlags.Public | BindingFlags.Static)
+ .Any(m => m.ReturnType == to && m.Name == "op_Implicit");
+ }
+ }
+
+ /// <summary>
+ /// This class is used as a flag when we get a parameter list for a method/constructor, but
+ /// we do not know one of the types because null was passed in.
+ /// </summary>
+ public class NUnitNullType
+ {
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if PORTABLE || SILVERLIGHT || NETCF
+namespace System.Web.UI
+{
+ /// <summary>
+ /// A shim of the .NET interface for platforms that do not support it.
+ /// Used to indicate that a control can be the target of a callback event on the server.
+ /// </summary>
+ public interface ICallbackEventHandler
+ {
+ /// <summary>
+ /// Processes a callback event that targets a control.
+ /// </summary>
+ /// <param name="report"></param>
+ void RaiseCallbackEvent(string report);
+
+ /// <summary>
+ /// Returns the results of a callback event that targets a control.
+ /// </summary>
+ /// <returns></returns>
+ string GetCallbackResult();
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if SILVERLIGHT || PORTABLE
+namespace System
+{
+ /// <summary>
+ /// A shim of the .NET attribute for platforms that do not support it.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)]
+ public sealed class SerializableAttribute : Attribute
+ {
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// AllItemsConstraint applies another constraint to each
+ /// item in a collection, succeeding if they all succeed.
+ /// </summary>
+ public class AllItemsConstraint : PrefixConstraint
+ {
+ /// <summary>
+ /// Construct an AllItemsConstraint on top of an existing constraint
+ /// </summary>
+ /// <param name="itemConstraint"></param>
+ public AllItemsConstraint(IConstraint itemConstraint)
+ : base(itemConstraint)
+ {
+ DescriptionPrefix = "all items";
+ }
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public override string DisplayName { get { return "All"; } }
+
+ /// <summary>
+ /// Apply the item constraint to each item in the collection,
+ /// failing if any item fails.
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ if (!(actual is IEnumerable))
+ throw new ArgumentException("The actual value must be an IEnumerable", "actual");
+
+ foreach (object item in (IEnumerable)actual)
+ if (!BaseConstraint.ApplyTo(item).IsSuccess)
+ return new ConstraintResult(this, actual, ConstraintStatus.Failure);
+
+ return new ConstraintResult(this, actual, ConstraintStatus.Success);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// AndConstraint succeeds only if both members succeed.
+ /// </summary>
+ public class AndConstraint : BinaryConstraint
+ {
+ //private enum FailurePoint
+ //{
+ // None,
+ // Left,
+ // Right
+ //};
+
+ //private FailurePoint failurePoint;
+
+ /// <summary>
+ /// Create an AndConstraint from two other constraints
+ /// </summary>
+ /// <param name="left">The first constraint</param>
+ /// <param name="right">The second constraint</param>
+ public AndConstraint(IConstraint left, IConstraint right) : base(left, right) { }
+
+ /// <summary>
+ /// Gets text describing a constraint
+ /// </summary>
+ public override string Description
+ {
+ get { return Left.Description + " and " + Right.Description; }
+ }
+
+ /// <summary>
+ /// Apply both member constraints to an actual value, succeeding
+ /// succeeding only if both of them succeed.
+ /// </summary>
+ /// <param name="actual">The actual value</param>
+ /// <returns>True if the constraints both succeeded</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ var leftResult = Left.ApplyTo(actual);
+ var rightResult = leftResult.IsSuccess
+ ? Right.ApplyTo(actual)
+ : new ConstraintResult(Right, actual);
+
+ return new AndConstraintResult(this, actual, leftResult, rightResult);
+ }
+
+ #region Nested Result Class
+
+ class AndConstraintResult : ConstraintResult
+ {
+ private ConstraintResult leftResult;
+ private ConstraintResult rightResult;
+
+ public AndConstraintResult(AndConstraint constraint, object actual, ConstraintResult leftResult, ConstraintResult rightResult)
+ : base(constraint, actual, leftResult.IsSuccess && rightResult.IsSuccess)
+ {
+ this.leftResult = leftResult;
+ this.rightResult = rightResult;
+ }
+
+ /// <summary>
+ /// Write the actual value for a failing constraint test to a
+ /// MessageWriter. The default implementation simply writes
+ /// the raw value of actual, leaving it to the writer to
+ /// perform any formatting.
+ /// </summary>
+ /// <param name="writer">The writer on which the actual value is displayed</param>
+ public override void WriteActualValueTo(MessageWriter writer)
+ {
+ if (this.IsSuccess)
+ base.WriteActualValueTo(writer);
+ else if (!leftResult.IsSuccess)
+ leftResult.WriteActualValueTo(writer);
+ else
+ rightResult.WriteActualValueTo(writer);
+ }
+ }
+
+ #endregion
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// AssignableFromConstraint is used to test that an object
+ /// can be assigned from a given Type.
+ /// </summary>
+ public class AssignableFromConstraint : TypeConstraint
+ {
+ /// <summary>
+ /// Construct an AssignableFromConstraint for the type provided
+ /// </summary>
+ /// <param name="type"></param>
+ public AssignableFromConstraint(Type type) : base(type, "assignable from ") { }
+
+ /// <summary>
+ /// Apply the constraint to an actual value, returning true if it succeeds
+ /// </summary>
+ /// <param name="actual">The actual argument</param>
+ /// <returns>True if the constraint succeeds, otherwise false.</returns>
+ protected override bool Matches(object actual)
+ {
+ return actual != null && actual.GetType().GetTypeInfo().IsAssignableFrom(expectedType.GetTypeInfo());
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// AssignableToConstraint is used to test that an object
+ /// can be assigned to a given Type.
+ /// </summary>
+ public class AssignableToConstraint : TypeConstraint
+ {
+ /// <summary>
+ /// Construct an AssignableToConstraint for the type provided
+ /// </summary>
+ /// <param name="type"></param>
+ public AssignableToConstraint(Type type) : base(type, "assignable to ") { }
+
+ /// <summary>
+ /// Apply the constraint to an actual value, returning true if it succeeds
+ /// </summary>
+ /// <param name="actual">The actual argument</param>
+ /// <returns>True if the constraint succeeds, otherwise false.</returns>
+ protected override bool Matches(object actual)
+ {
+ return expectedType != null && actual != null && expectedType.GetTypeInfo().IsAssignableFrom(actual.GetType().GetTypeInfo());
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// AttributeConstraint tests that a specified attribute is present
+ /// on a Type or other provider and that the value of the attribute
+ /// satisfies some other constraint.
+ /// </summary>
+ public class AttributeConstraint : PrefixConstraint
+ {
+ private readonly Type expectedType;
+ private Attribute attrFound;
+
+ /// <summary>
+ /// Constructs an AttributeConstraint for a specified attribute
+ /// Type and base constraint.
+ /// </summary>
+ /// <param name="type"></param>
+ /// <param name="baseConstraint"></param>
+ public AttributeConstraint(Type type, IConstraint baseConstraint)
+ : base(baseConstraint)
+ {
+ this.expectedType = type;
+ this.DescriptionPrefix = "attribute " + expectedType.FullName;
+
+ if (!typeof(Attribute).GetTypeInfo().IsAssignableFrom(expectedType.GetTypeInfo()))
+ throw new ArgumentException(string.Format(
+ "Type {0} is not an attribute", expectedType), "type");
+ }
+
+ /// <summary>
+ /// Determines whether the Type or other provider has the
+ /// expected attribute and if its value matches the
+ /// additional constraint specified.
+ /// </summary>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ Guard.ArgumentNotNull(actual, "actual");
+ Attribute[] attrs = AttributeHelper.GetCustomAttributes(actual, expectedType, true);
+ if (attrs.Length == 0)
+ throw new ArgumentException(string.Format("Attribute {0} was not found", expectedType), "actual");
+
+ attrFound = attrs[0];
+ return BaseConstraint.ApplyTo(attrFound);
+ }
+
+ /// <summary>
+ /// Returns a string representation of the constraint.
+ /// </summary>
+ protected override string GetStringRepresentation()
+ {
+ return string.Format("<attribute {0} {1}>", expectedType, BaseConstraint);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// AttributeExistsConstraint tests for the presence of a
+ /// specified attribute on a Type.
+ /// </summary>
+ public class AttributeExistsConstraint : Constraint
+ {
+ private Type expectedType;
+
+ /// <summary>
+ /// Constructs an AttributeExistsConstraint for a specific attribute Type
+ /// </summary>
+ /// <param name="type"></param>
+ public AttributeExistsConstraint(Type type)
+ : base(type)
+ {
+ this.expectedType = type;
+
+ if (!typeof(Attribute).GetTypeInfo().IsAssignableFrom(expectedType.GetTypeInfo()))
+ throw new ArgumentException(string.Format(
+ "Type {0} is not an attribute", expectedType), "type");
+ }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "type with attribute " + MsgUtils.FormatValue(expectedType); }
+ }
+
+ /// <summary>
+ /// Tests whether the object provides the expected attribute.
+ /// </summary>
+ /// <param name="actual">A Type, MethodInfo, or other ICustomAttributeProvider</param>
+ /// <returns>True if the expected attribute is present, otherwise false</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ Guard.ArgumentNotNull(actual, "actual");
+ Attribute[] attrs = AttributeHelper.GetCustomAttributes(actual, expectedType, true);
+ ConstraintResult result = new ConstraintResult(this, actual);
+ result.Status = attrs.Length > 0
+ ? ConstraintStatus.Success : ConstraintStatus.Failure;
+ return result;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// BinaryConstraint is the abstract base of all constraints
+ /// that combine two other constraints in some fashion.
+ /// </summary>
+ public abstract class BinaryConstraint : Constraint
+ {
+ /// <summary>
+ /// The first constraint being combined
+ /// </summary>
+ protected IConstraint Left;
+ /// <summary>
+ /// The second constraint being combined
+ /// </summary>
+ protected IConstraint Right;
+
+ /// <summary>
+ /// Construct a BinaryConstraint from two other constraints
+ /// </summary>
+ /// <param name="left">The first constraint</param>
+ /// <param name="right">The second constraint</param>
+ protected BinaryConstraint(IConstraint left, IConstraint right)
+ : base(left, right)
+ {
+ Guard.ArgumentNotNull(left, "left");
+ this.Left = left;
+
+ Guard.ArgumentNotNull(right, "right");
+ this.Right = right;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+using System;
+using System.IO;
+using System.Runtime.Serialization;
+using System.Runtime.Serialization.Formatters.Binary;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// BinarySerializableConstraint tests whether
+ /// an object is serializable in binary format.
+ /// </summary>
+ public class BinarySerializableConstraint : Constraint
+ {
+ readonly BinaryFormatter serializer = new BinaryFormatter();
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "binary serializable"; }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ if (actual == null)
+ throw new ArgumentNullException("actual");
+
+ MemoryStream stream = new MemoryStream();
+ bool succeeded = false;
+
+ try
+ {
+ serializer.Serialize(stream, actual);
+
+ stream.Seek(0, SeekOrigin.Begin);
+
+ succeeded = serializer.Deserialize(stream) != null;
+ }
+ catch (SerializationException)
+ {
+ // Ignore and return failure
+ }
+
+ return new ConstraintResult(this, actual.GetType(), succeeded);
+ }
+
+ /// <summary>
+ /// Returns the string representation
+ /// </summary>
+ protected override string GetStringRepresentation()
+ {
+ return "<binaryserializable>";
+ }
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// CollectionConstraint is the abstract base class for
+ /// constraints that operate on collections.
+ /// </summary>
+ public abstract class CollectionConstraint : Constraint
+ {
+ /// <summary>
+ /// Construct an empty CollectionConstraint
+ /// </summary>
+ protected CollectionConstraint() { }
+
+ /// <summary>
+ /// Construct a CollectionConstraint
+ /// </summary>
+ /// <param name="arg"></param>
+ protected CollectionConstraint(object arg) : base(arg) { }
+
+ /// <summary>
+ /// Determines whether the specified enumerable is empty.
+ /// </summary>
+ /// <param name="enumerable">The enumerable.</param>
+ /// <returns>
+ /// <c>true</c> if the specified enumerable is empty; otherwise, <c>false</c>.
+ /// </returns>
+ protected static bool IsEmpty(IEnumerable enumerable)
+ {
+ ICollection collection = enumerable as ICollection;
+ if (collection != null)
+ return collection.Count == 0;
+
+ foreach (object o in enumerable)
+ return false;
+
+ return true;
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ // TODO: Use an error result if actual is not IEnumerable
+ IEnumerable enumerable = actual as IEnumerable;
+ if (enumerable == null)
+ throw new ArgumentException("The actual value must be an IEnumerable", "actual");
+ //return new ConstraintResult(this, actual, "The actual value must be an IEnumerable");
+
+ return new ConstraintResult(this, actual, Matches(enumerable));
+ }
+
+ /// <summary>
+ /// Protected method to be implemented by derived classes
+ /// </summary>
+ /// <param name="collection"></param>
+ /// <returns></returns>
+ protected abstract bool Matches(IEnumerable collection);
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// CollectionContainsConstraint is used to test whether a collection
+ /// contains an expected object as a member.
+ /// </summary>
+ public class CollectionContainsConstraint : CollectionItemsEqualConstraint
+ {
+ /// <summary>
+ /// Construct a CollectionContainsConstraint
+ /// </summary>
+ /// <param name="expected"></param>
+ public CollectionContainsConstraint(object expected)
+ : base(expected)
+ {
+ Expected = expected;
+ }
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public override string DisplayName { get { return "Contains"; } }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "collection containing " + MsgUtils.FormatValue(Expected); }
+ }
+
+ /// <summary>
+ /// Gets the expected object
+ /// </summary>
+ protected object Expected { get; private set; }
+
+ /// <summary>
+ /// Test whether the expected item is contained in the collection
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ protected override bool Matches(IEnumerable actual)
+ {
+ foreach (object obj in actual)
+ if (ItemsEqual(obj, Expected))
+ return true;
+
+ return false;
+ }
+
+
+ /// <summary>
+ /// Flag the constraint to use the supplied predicate function
+ /// </summary>
+ /// <param name="comparison">The comparison function to use.</param>
+ /// <returns>Self.</returns>
+ public CollectionContainsConstraint Using<TCollectionType, TMemberType>(Func<TCollectionType, TMemberType, bool> comparison)
+ {
+ // reverse the order of the arguments to match expectations of PredicateEqualityComparer
+ Func<TMemberType, TCollectionType, bool> invertedComparison = (actual, expected) => comparison.Invoke(expected, actual);
+
+ base.Using(EqualityAdapter.For(invertedComparison));
+ return this;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// CollectionEquivalentConstraint is used to determine whether two
+ /// collections are equivalent.
+ /// </summary>
+ public class CollectionEquivalentConstraint : CollectionItemsEqualConstraint
+ {
+ private readonly IEnumerable _expected;
+
+ /// <summary>
+ /// Construct a CollectionEquivalentConstraint
+ /// </summary>
+ /// <param name="expected"></param>
+ public CollectionEquivalentConstraint(IEnumerable expected)
+ : base(expected)
+ {
+ _expected = expected;
+ }
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public override string DisplayName { get { return "Equivalent"; } }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "equivalent to " + MsgUtils.FormatValue(_expected); }
+ }
+
+ /// <summary>
+ /// Test whether two collections are equivalent
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ protected override bool Matches(IEnumerable actual)
+ {
+ // This is just an optimization
+ if (_expected is ICollection && actual is ICollection)
+ if (((ICollection)actual).Count != ((ICollection)_expected).Count)
+ return false;
+
+ CollectionTally tally = Tally(_expected);
+ return tally.TryRemove(actual) && tally.Count == 0;
+ }
+
+ /// <summary>
+ /// Flag the constraint to use the supplied predicate function
+ /// </summary>
+ /// <param name="comparison">The comparison function to use.</param>
+ /// <returns>Self.</returns>
+ public CollectionEquivalentConstraint Using<TActual, TExpected>(Func<TActual, TExpected, bool> comparison)
+ {
+ base.Using(EqualityAdapter.For(comparison));
+ return this;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// CollectionItemsEqualConstraint is the abstract base class for all
+ /// collection constraints that apply some notion of item equality
+ /// as a part of their operation.
+ /// </summary>
+ public abstract class CollectionItemsEqualConstraint : CollectionConstraint
+ {
+ private readonly NUnitEqualityComparer comparer = NUnitEqualityComparer.Default;
+
+ /// <summary>
+ /// Construct an empty CollectionConstraint
+ /// </summary>
+ protected CollectionItemsEqualConstraint() { }
+
+ /// <summary>
+ /// Construct a CollectionConstraint
+ /// </summary>
+ /// <param name="arg"></param>
+ protected CollectionItemsEqualConstraint(object arg) : base(arg) { }
+
+ #region Modifiers
+
+ /// <summary>
+ /// Flag the constraint to ignore case and return self.
+ /// </summary>
+ public CollectionItemsEqualConstraint IgnoreCase
+ {
+ get
+ {
+ comparer.IgnoreCase = true;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Flag the constraint to use the supplied IComparer object.
+ /// </summary>
+ /// <param name="comparer">The IComparer object to use.</param>
+ /// <returns>Self.</returns>
+ public CollectionItemsEqualConstraint Using(IComparer comparer)
+ {
+ this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
+ return this;
+ }
+
+ /// <summary>
+ /// Flag the constraint to use the supplied IComparer object.
+ /// </summary>
+ /// <param name="comparer">The IComparer object to use.</param>
+ /// <returns>Self.</returns>
+ public CollectionItemsEqualConstraint Using<T>(IComparer<T> comparer)
+ {
+ this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
+ return this;
+ }
+
+ /// <summary>
+ /// Flag the constraint to use the supplied Comparison object.
+ /// </summary>
+ /// <param name="comparer">The IComparer object to use.</param>
+ /// <returns>Self.</returns>
+ public CollectionItemsEqualConstraint Using<T>(Comparison<T> comparer)
+ {
+ this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
+ return this;
+ }
+
+ /// <summary>
+ /// Flag the constraint to use the supplied IEqualityComparer object.
+ /// </summary>
+ /// <param name="comparer">The IComparer object to use.</param>
+ /// <returns>Self.</returns>
+ public CollectionItemsEqualConstraint Using(IEqualityComparer comparer)
+ {
+ this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
+ return this;
+ }
+
+ /// <summary>
+ /// Flag the constraint to use the supplied IEqualityComparer object.
+ /// </summary>
+ /// <param name="comparer">The IComparer object to use.</param>
+ /// <returns>Self.</returns>
+ public CollectionItemsEqualConstraint Using<T>(IEqualityComparer<T> comparer)
+ {
+ this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
+ return this;
+ }
+
+ internal CollectionItemsEqualConstraint Using(EqualityAdapter adapter)
+ {
+ comparer.ExternalComparers.Add(adapter);
+ return this;
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Compares two collection members for equality
+ /// </summary>
+ protected bool ItemsEqual(object x, object y)
+ {
+ Tolerance tolerance = Tolerance.Default;
+ return comparer.AreEqual(x, y, ref tolerance);
+ }
+
+ /// <summary>
+ /// Return a new CollectionTally for use in making tests
+ /// </summary>
+ /// <param name="c">The collection to be included in the tally</param>
+ protected CollectionTally Tally(IEnumerable c)
+ {
+ return new CollectionTally(comparer, c);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Reflection;
+using System.Text;
+using System.Collections.Generic;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// CollectionOrderedConstraint is used to test whether a collection is ordered.
+ /// </summary>
+ public class CollectionOrderedConstraint : CollectionConstraint
+ {
+ private ComparisonAdapter comparer = ComparisonAdapter.Default;
+ private string comparerName;
+ private string propertyName;
+ private bool descending;
+
+ /// <summary>
+ /// Construct a CollectionOrderedConstraint
+ /// </summary>
+ public CollectionOrderedConstraint()
+ {
+ }
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public override string DisplayName { get { return "Ordered"; } }
+
+ ///<summary>
+ /// If used performs a reverse comparison
+ ///</summary>
+ public CollectionOrderedConstraint Descending
+ {
+ get
+ {
+ descending = true;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Modifies the constraint to use an <see cref="IComparer"/> and returns self.
+ /// </summary>
+ public CollectionOrderedConstraint Using(IComparer comparer)
+ {
+ this.comparer = ComparisonAdapter.For(comparer);
+ this.comparerName = comparer.GetType().FullName;
+ return this;
+ }
+
+ /// <summary>
+ /// Modifies the constraint to use an <see cref="IComparer{T}"/> and returns self.
+ /// </summary>
+ public CollectionOrderedConstraint Using<T>(IComparer<T> comparer)
+ {
+ this.comparer = ComparisonAdapter.For(comparer);
+ this.comparerName = comparer.GetType().FullName;
+ return this;
+ }
+
+ /// <summary>
+ /// Modifies the constraint to use a <see cref="Comparison{T}"/> and returns self.
+ /// </summary>
+ public CollectionOrderedConstraint Using<T>(Comparison<T> comparer)
+ {
+ this.comparer = ComparisonAdapter.For(comparer);
+ this.comparerName = comparer.GetType().FullName;
+ return this;
+ }
+
+ /// <summary>
+ /// Modifies the constraint to test ordering by the value of
+ /// a specified property and returns self.
+ /// </summary>
+ public CollectionOrderedConstraint By(string propertyName)
+ {
+ this.propertyName = propertyName;
+ return this;
+ }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get
+ {
+ string desc = propertyName == null
+ ? "collection ordered"
+ : "collection ordered by "+ MsgUtils.FormatValue(propertyName);
+
+ if (descending)
+ desc += ", descending";
+
+ return desc;
+ }
+ }
+
+ /// <summary>
+ /// Test whether the collection is ordered
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ protected override bool Matches(IEnumerable actual)
+ {
+ object previous = null;
+ int index = 0;
+ foreach (object obj in actual)
+ {
+ object objToCompare = obj;
+ if (obj == null)
+ throw new ArgumentNullException("actual", "Null value at index " + index.ToString());
+
+ if (this.propertyName != null)
+ {
+ PropertyInfo prop = obj.GetType().GetProperty(propertyName);
+ objToCompare = prop.GetValue(obj, null);
+ if (objToCompare == null)
+ throw new ArgumentNullException("actual", "Null property value at index " + index.ToString());
+ }
+
+ if (previous != null)
+ {
+ //int comparisonResult = comparer.Compare(al[i], al[i + 1]);
+ int comparisonResult = comparer.Compare(previous, objToCompare);
+
+ if (descending && comparisonResult < 0)
+ return false;
+ if (!descending && comparisonResult > 0)
+ return false;
+ }
+
+ previous = objToCompare;
+ index++;
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Returns the string representation of the constraint.
+ /// </summary>
+ /// <returns></returns>
+ protected override string GetStringRepresentation()
+ {
+ StringBuilder sb = new StringBuilder("<ordered");
+
+ if (propertyName != null)
+ sb.Append("by " + propertyName);
+ if (descending)
+ sb.Append(" descending");
+ if (comparerName != null)
+ sb.Append(" " + comparerName);
+
+ sb.Append(">");
+
+ return sb.ToString();
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// CollectionSubsetConstraint is used to determine whether
+ /// one collection is a subset of another
+ /// </summary>
+ public class CollectionSubsetConstraint : CollectionItemsEqualConstraint
+ {
+ private IEnumerable _expected;
+
+ /// <summary>
+ /// Construct a CollectionSubsetConstraint
+ /// </summary>
+ /// <param name="expected">The collection that the actual value is expected to be a subset of</param>
+ public CollectionSubsetConstraint(IEnumerable expected) : base(expected)
+ {
+ _expected = expected;
+ }
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public override string DisplayName { get { return "SubsetOf"; } }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "subset of " + MsgUtils.FormatValue(_expected); }
+ }
+
+ /// <summary>
+ /// Test whether the actual collection is a subset of
+ /// the expected collection provided.
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ protected override bool Matches(IEnumerable actual)
+ {
+ return Tally(_expected).TryRemove( actual );
+ }
+
+
+ /// <summary>
+ /// Flag the constraint to use the supplied predicate function
+ /// </summary>
+ /// <param name="comparison">The comparison function to use.</param>
+ /// <returns>Self.</returns>
+ public CollectionSubsetConstraint Using<TSubsetType, TSupersetType>(Func<TSubsetType, TSupersetType, bool> comparison)
+ {
+ base.Using(EqualityAdapter.For(comparison));
+ return this;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// CollectionSupersetConstraint is used to determine whether
+ /// one collection is a superset of another
+ /// </summary>
+ public class CollectionSupersetConstraint : CollectionItemsEqualConstraint
+ {
+ private IEnumerable _expected;
+
+ /// <summary>
+ /// Construct a CollectionSupersetConstraint
+ /// </summary>
+ /// <param name="expected">The collection that the actual value is expected to be a superset of</param>
+ public CollectionSupersetConstraint(IEnumerable expected)
+ : base(expected)
+ {
+ _expected = expected;
+ }
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public override string DisplayName { get { return "SupersetOf"; } }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "superset of " + MsgUtils.FormatValue(_expected); }
+ }
+
+ /// <summary>
+ /// Test whether the actual collection is a superset of
+ /// the expected collection provided.
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ protected override bool Matches(IEnumerable actual)
+ {
+ return Tally(actual).TryRemove(_expected);
+ }
+
+ /// <summary>
+ /// Flag the constraint to use the supplied predicate function
+ /// </summary>
+ /// <param name="comparison">The comparison function to use.</param>
+ /// <returns>Self.</returns>
+ public CollectionSupersetConstraint Using<TSupersetType, TSubsetType>(Func<TSupersetType, TSubsetType, bool> comparison)
+ {
+ // internal code reverses the expected order of the arguments.
+ Func<TSubsetType, TSupersetType, bool> invertedComparison = (actual, expected) => comparison.Invoke(expected, actual);
+ base.Using(EqualityAdapter.For(invertedComparison));
+ return this;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections;
+using System.Collections.Generic;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// CollectionTally counts (tallies) the number of
+ /// occurrences of each object in one or more enumerations.
+ /// </summary>
+ public class CollectionTally
+ {
+ // Internal list used to track occurrences
+ private readonly List<object> list = new List<object>();
+
+ private readonly NUnitEqualityComparer comparer;
+
+ /// <summary>
+ /// Construct a CollectionTally object from a comparer and a collection
+ /// </summary>
+ public CollectionTally(NUnitEqualityComparer comparer, IEnumerable c)
+ {
+ this.comparer = comparer;
+
+ foreach (object o in c)
+ list.Add(o);
+ }
+
+ /// <summary>
+ /// The number of objects remaining in the tally
+ /// </summary>
+ public int Count
+ {
+ get { return list.Count; }
+ }
+
+ private bool ItemsEqual(object expected, object actual)
+ {
+ Tolerance tolerance = Tolerance.Default;
+ return comparer.AreEqual(expected, actual, ref tolerance);
+ }
+
+ /// <summary>
+ /// Try to remove an object from the tally
+ /// </summary>
+ /// <param name="o">The object to remove</param>
+ /// <returns>True if successful, false if the object was not found</returns>
+ public bool TryRemove(object o)
+ {
+ for (int index = 0; index < list.Count; index++)
+ if (ItemsEqual(list[index], o))
+ {
+ list.RemoveAt(index);
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Try to remove a set of objects from the tally
+ /// </summary>
+ /// <param name="c">The objects to remove</param>
+ /// <returns>True if successful, false if any object was not found</returns>
+ public bool TryRemove(IEnumerable c)
+ {
+ foreach (object o in c)
+ if (!TryRemove(o))
+ return false;
+
+ return true;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// ComparisonAdapter class centralizes all comparisons of
+ /// _values in NUnit, adapting to the use of any provided
+ /// <see cref="IComparer"/>, <see cref="IComparer{T}"/>
+ /// or <see cref="Comparison{T}"/>.
+ /// </summary>
+ public abstract class ComparisonAdapter
+ {
+ /// <summary>
+ /// Gets the default ComparisonAdapter, which wraps an
+ /// NUnitComparer object.
+ /// </summary>
+ public static ComparisonAdapter Default
+ {
+ get { return new DefaultComparisonAdapter(); }
+ }
+
+ /// <summary>
+ /// Returns a ComparisonAdapter that wraps an <see cref="IComparer"/>
+ /// </summary>
+ public static ComparisonAdapter For(IComparer comparer)
+ {
+ return new ComparerAdapter(comparer);
+ }
+
+ /// <summary>
+ /// Returns a ComparisonAdapter that wraps an <see cref="IComparer{T}"/>
+ /// </summary>
+ public static ComparisonAdapter For<T>(IComparer<T> comparer)
+ {
+ return new ComparerAdapter<T>(comparer);
+ }
+
+ /// <summary>
+ /// Returns a ComparisonAdapter that wraps a <see cref="Comparison{T}"/>
+ /// </summary>
+ public static ComparisonAdapter For<T>(Comparison<T> comparer)
+ {
+ return new ComparisonAdapterForComparison<T>(comparer);
+ }
+
+ /// <summary>
+ /// Compares two objects
+ /// </summary>
+ public abstract int Compare(object expected, object actual);
+
+ class DefaultComparisonAdapter : ComparerAdapter
+ {
+ /// <summary>
+ /// Construct a default ComparisonAdapter
+ /// </summary>
+ public DefaultComparisonAdapter() : base( NUnitComparer.Default ) { }
+ }
+
+ class ComparerAdapter : ComparisonAdapter
+ {
+ private readonly IComparer comparer;
+
+ /// <summary>
+ /// Construct a ComparisonAdapter for an <see cref="IComparer"/>
+ /// </summary>
+ public ComparerAdapter(IComparer comparer)
+ {
+ this.comparer = comparer;
+ }
+
+ /// <summary>
+ /// Compares two objects
+ /// </summary>
+ /// <param name="expected"></param>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ public override int Compare(object expected, object actual)
+ {
+ return comparer.Compare(expected, actual);
+ }
+ }
+
+ /// <summary>
+ /// ComparerAdapter extends <see cref="ComparisonAdapter"/> and
+ /// allows use of an <see cref="IComparer{T}"/> or <see cref="Comparison{T}"/>
+ /// to actually perform the comparison.
+ /// </summary>
+ class ComparerAdapter<T> : ComparisonAdapter
+ {
+ private readonly IComparer<T> comparer;
+
+ /// <summary>
+ /// Construct a ComparisonAdapter for an <see cref="IComparer{T}"/>
+ /// </summary>
+ public ComparerAdapter(IComparer<T> comparer)
+ {
+ this.comparer = comparer;
+ }
+
+ /// <summary>
+ /// Compare a Type T to an object
+ /// </summary>
+ public override int Compare(object expected, object actual)
+ {
+ if (!typeof(T).GetTypeInfo().IsAssignableFrom(expected.GetType().GetTypeInfo()))
+ throw new ArgumentException("Cannot compare " + expected.ToString());
+
+ if (!typeof(T).GetTypeInfo().IsAssignableFrom(actual.GetType().GetTypeInfo()))
+ throw new ArgumentException("Cannot compare to " + actual.ToString());
+
+ return comparer.Compare((T)expected, (T)actual);
+ }
+ }
+
+ class ComparisonAdapterForComparison<T> : ComparisonAdapter
+ {
+ private readonly Comparison<T> comparison;
+
+ /// <summary>
+ /// Construct a ComparisonAdapter for a <see cref="Comparison{T}"/>
+ /// </summary>
+ public ComparisonAdapterForComparison(Comparison<T> comparer)
+ {
+ this.comparison = comparer;
+ }
+
+ /// <summary>
+ /// Compare a Type T to an object
+ /// </summary>
+ public override int Compare(object expected, object actual)
+ {
+ if (!typeof(T).GetTypeInfo().IsAssignableFrom(expected.GetType().GetTypeInfo()))
+ throw new ArgumentException("Cannot compare " + expected.ToString());
+
+ if (!typeof(T).GetTypeInfo().IsAssignableFrom(actual.GetType().GetTypeInfo()))
+ throw new ArgumentException("Cannot compare to " + actual.ToString());
+
+ return comparison.Invoke((T)expected, (T)actual);
+ }
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Abstract base class for constraints that compare _values to
+ /// determine if one is greater than, equal to or less than
+ /// the other.
+ /// </summary>
+ public abstract class ComparisonConstraint : Constraint
+ {
+ /// <summary>
+ /// The value against which a comparison is to be made
+ /// </summary>
+ protected object expected;
+ /// <summary>
+ /// If true, less than returns success
+ /// </summary>
+ protected bool lessComparisonResult = false;
+ /// <summary>
+ /// if true, equal returns success
+ /// </summary>
+ protected bool equalComparisonResult = false;
+ /// <summary>
+ /// if true, greater than returns success
+ /// </summary>
+ protected bool greaterComparisonResult = false;
+
+ /// <summary>
+ /// ComparisonAdapter to be used in making the comparison
+ /// </summary>
+ private ComparisonAdapter comparer = ComparisonAdapter.Default;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ComparisonConstraint"/> class.
+ /// </summary>
+ /// <param name="value">The value against which to make a comparison.</param>
+ /// <param name="lessComparisonResult">if set to <c>true</c> less succeeds.</param>
+ /// <param name="equalComparisonResult">if set to <c>true</c> equal succeeds.</param>
+ /// <param name="greaterComparisonResult">if set to <c>true</c> greater succeeds.</param>
+ /// <param name="predicate">String used in describing the constraint.</param>
+ protected ComparisonConstraint(object value, bool lessComparisonResult, bool equalComparisonResult, bool greaterComparisonResult, string predicate)
+ : base(value)
+ {
+ this.expected = value;
+ this.lessComparisonResult = lessComparisonResult;
+ this.equalComparisonResult = equalComparisonResult;
+ this.greaterComparisonResult = greaterComparisonResult;
+ this.Description = predicate + " " + MsgUtils.FormatValue(expected);
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ if (expected == null)
+ throw new ArgumentException("Cannot compare using a null reference", "expected");
+
+ if (actual == null)
+ throw new ArgumentException("Cannot compare to null reference", "actual");
+
+ int icomp = comparer.Compare(expected, actual);
+
+ bool hasSucceeded = icomp < 0 && greaterComparisonResult || icomp == 0 && equalComparisonResult || icomp > 0 && lessComparisonResult;
+ return new ConstraintResult(this, actual, hasSucceeded);
+ }
+
+ /// <summary>
+ /// Modifies the constraint to use an <see cref="IComparer"/> and returns self
+ /// </summary>
+ /// <param name="comparer">The comparer used for comparison tests</param>
+ /// <returns>A constraint modified to use the given comparer</returns>
+ public ComparisonConstraint Using(IComparer comparer)
+ {
+ this.comparer = ComparisonAdapter.For(comparer);
+ return this;
+ }
+
+ /// <summary>
+ /// Modifies the constraint to use an <see cref="IComparer{T}"/> and returns self
+ /// </summary>
+ /// <param name="comparer">The comparer used for comparison tests</param>
+ /// <returns>A constraint modified to use the given comparer</returns>
+ public ComparisonConstraint Using<T>(IComparer<T> comparer)
+ {
+ this.comparer = ComparisonAdapter.For(comparer);
+ return this;
+ }
+
+ /// <summary>
+ /// Modifies the constraint to use a <see cref="Comparison{T}"/> and returns self
+ /// </summary>
+ /// <param name="comparer">The comparer used for comparison tests</param>
+ /// <returns>A constraint modified to use the given comparer</returns>
+ public ComparisonConstraint Using<T>(Comparison<T> comparer)
+ {
+ this.comparer = ComparisonAdapter.For(comparer);
+ return this;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using NUnit.Framework.Internal;
+using NUnit.Compatibility;
+using System.Collections;
+using System;
+using System.Reflection;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Delegate used to delay evaluation of the actual value
+ /// to be used in evaluating a constraint
+ /// </summary>
+ public delegate TActual ActualValueDelegate<TActual>();
+
+ /// <summary>
+ /// The Constraint class is the base of all built-in constraints
+ /// within NUnit. It provides the operator overloads used to combine
+ /// constraints.
+ /// </summary>
+ public abstract class Constraint : IConstraint
+ {
+ Lazy<string> _displayName;
+
+ #region Constructor
+
+ /// <summary>
+ /// Construct a constraint with optional arguments
+ /// </summary>
+ /// <param name="args">Arguments to be saved</param>
+ protected Constraint(params object[] args)
+ {
+ Arguments = args;
+
+ _displayName = new Lazy<string>(() =>
+ {
+ var type = this.GetType();
+ var displayName = type.Name;
+ if (type.GetTypeInfo().IsGenericType)
+ displayName = displayName.Substring(0, displayName.Length - 2);
+ if (displayName.EndsWith("Constraint", StringComparison.Ordinal))
+ displayName = displayName.Substring(0, displayName.Length - 10);
+ return displayName;
+ });
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public virtual string DisplayName { get { return _displayName.Value; } }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public virtual string Description { get; protected set; }
+
+ /// <summary>
+ /// Arguments provided to this Constraint, for use in
+ /// formatting the description.
+ /// </summary>
+ public object[] Arguments { get; private set; }
+
+ /// <summary>
+ /// The ConstraintBuilder holding this constraint
+ /// </summary>
+ public ConstraintBuilder Builder { get; set; }
+
+ #endregion
+
+ #region Abstract and Virtual Methods
+
+ /// <summary>
+ /// Applies the constraint to an actual value, returning a ConstraintResult.
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>A ConstraintResult</returns>
+ public abstract ConstraintResult ApplyTo<TActual>(TActual actual);
+
+ /// <summary>
+ /// Applies the constraint to an ActualValueDelegate that returns
+ /// the value to be tested. The default implementation simply evaluates
+ /// the delegate but derived classes may override it to provide for
+ /// delayed processing.
+ /// </summary>
+ /// <param name="del">An ActualValueDelegate</param>
+ /// <returns>A ConstraintResult</returns>
+ public virtual ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del)
+ {
+#if NET_4_0 || NET_4_5 || PORTABLE
+ if (AsyncInvocationRegion.IsAsyncOperation(del))
+ using (var region = AsyncInvocationRegion.Create(del))
+ return ApplyTo(region.WaitForPendingOperationsToComplete(del()));
+#endif
+ return ApplyTo(GetTestObject(del));
+ }
+
+#pragma warning disable 3006
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given reference.
+ /// The default implementation simply dereferences the value but
+ /// derived classes may override it to provide for delayed processing.
+ /// </summary>
+ /// <param name="actual">A reference to the value to be tested</param>
+ /// <returns>A ConstraintResult</returns>
+ public virtual ConstraintResult ApplyTo<TActual>(ref TActual actual)
+ {
+ return ApplyTo(actual);
+ }
+#pragma warning restore 3006
+
+ /// <summary>
+ /// Retrieves the value to be tested from an ActualValueDelegate.
+ /// The default implementation simply evaluates the delegate but derived
+ /// classes may override it to provide for delayed processing.
+ /// </summary>
+ /// <param name="del">An ActualValueDelegate</param>
+ /// <returns>Delegate evaluation result</returns>
+ protected virtual object GetTestObject<TActual>(ActualValueDelegate<TActual> del)
+ {
+ return del();
+ }
+
+ #endregion
+
+ #region ToString Override
+
+ /// <summary>
+ /// Default override of ToString returns the constraint DisplayName
+ /// followed by any arguments within angle brackets.
+ /// </summary>
+ /// <returns></returns>
+ public override string ToString()
+ {
+ string rep = GetStringRepresentation();
+
+ return this.Builder == null ? rep : string.Format("<unresolved {0}>", rep);
+ }
+
+ /// <summary>
+ /// Returns the string representation of this constraint
+ /// </summary>
+ protected virtual string GetStringRepresentation()
+ {
+ System.Text.StringBuilder sb = new System.Text.StringBuilder();
+
+ sb.Append("<");
+ sb.Append(DisplayName.ToLower());
+
+ foreach (object arg in Arguments)
+ {
+ sb.Append(" ");
+ sb.Append(_displayable(arg));
+ }
+
+ sb.Append(">");
+
+ return sb.ToString();
+ }
+
+ private static string _displayable(object o)
+ {
+ if (o == null) return "null";
+
+ string fmt = o is string ? "\"{0}\"" : "{0}";
+ return string.Format(System.Globalization.CultureInfo.InvariantCulture, fmt, o);
+ }
+
+ #endregion
+
+ #region Operator Overloads
+
+ /// <summary>
+ /// This operator creates a constraint that is satisfied only if both
+ /// argument constraints are satisfied.
+ /// </summary>
+ public static Constraint operator &(Constraint left, Constraint right)
+ {
+ IResolveConstraint l = (IResolveConstraint)left;
+ IResolveConstraint r = (IResolveConstraint)right;
+ return new AndConstraint(l.Resolve(), r.Resolve());
+ }
+
+ /// <summary>
+ /// This operator creates a constraint that is satisfied if either
+ /// of the argument constraints is satisfied.
+ /// </summary>
+ public static Constraint operator |(Constraint left, Constraint right)
+ {
+ IResolveConstraint l = (IResolveConstraint)left;
+ IResolveConstraint r = (IResolveConstraint)right;
+ return new OrConstraint(l.Resolve(), r.Resolve());
+ }
+
+ /// <summary>
+ /// This operator creates a constraint that is satisfied if the
+ /// argument constraint is not satisfied.
+ /// </summary>
+ public static Constraint operator !(Constraint constraint)
+ {
+ IResolveConstraint r = (IResolveConstraint)constraint;
+ return new NotConstraint(r.Resolve());
+ }
+
+ #endregion
+
+ #region Binary Operators
+
+ /// <summary>
+ /// Returns a ConstraintExpression by appending And
+ /// to the current constraint.
+ /// </summary>
+ public ConstraintExpression And
+ {
+ get
+ {
+ ConstraintBuilder builder = this.Builder;
+ if (builder == null)
+ {
+ builder = new ConstraintBuilder();
+ builder.Append(this);
+ }
+
+ builder.Append(new AndOperator());
+
+ return new ConstraintExpression(builder);
+ }
+ }
+
+ /// <summary>
+ /// Returns a ConstraintExpression by appending And
+ /// to the current constraint.
+ /// </summary>
+ public ConstraintExpression With
+ {
+ get { return this.And; }
+ }
+
+ /// <summary>
+ /// Returns a ConstraintExpression by appending Or
+ /// to the current constraint.
+ /// </summary>
+ public ConstraintExpression Or
+ {
+ get
+ {
+ ConstraintBuilder builder = this.Builder;
+ if (builder == null)
+ {
+ builder = new ConstraintBuilder();
+ builder.Append(this);
+ }
+
+ builder.Append(new OrOperator());
+
+ return new ConstraintExpression(builder);
+ }
+ }
+
+ #endregion
+
+ #region After Modifier
+
+#if !PORTABLE
+ /// <summary>
+ /// Returns a DelayedConstraint with the specified delay time.
+ /// </summary>
+ /// <param name="delayInMilliseconds">The delay in milliseconds.</param>
+ /// <returns></returns>
+ public DelayedConstraint After(int delayInMilliseconds)
+ {
+ return new DelayedConstraint(
+ Builder == null ? this : Builder.Resolve(),
+ delayInMilliseconds);
+ }
+
+ /// <summary>
+ /// Returns a DelayedConstraint with the specified delay time
+ /// and polling interval.
+ /// </summary>
+ /// <param name="delayInMilliseconds">The delay in milliseconds.</param>
+ /// <param name="pollingInterval">The interval at which to test the constraint.</param>
+ /// <returns></returns>
+ public DelayedConstraint After(int delayInMilliseconds, int pollingInterval)
+ {
+ return new DelayedConstraint(
+ Builder == null ? this : Builder.Resolve(),
+ delayInMilliseconds,
+ pollingInterval);
+ }
+#endif
+
+ #endregion
+
+ #region IResolveConstraint Members
+
+ /// <summary>
+ /// Resolves any pending operators and returns the resolved constraint.
+ /// </summary>
+ IConstraint IResolveConstraint.Resolve()
+ {
+ return Builder == null ? this : Builder.Resolve();
+ }
+
+ #endregion
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// ConstraintBuilder maintains the stacks that are used in
+ /// processing a ConstraintExpression. An OperatorStack
+ /// is used to hold operators that are waiting for their
+ /// operands to be reorganized. a ConstraintStack holds
+ /// input constraints as well as the results of each
+ /// operator applied.
+ /// </summary>
+ public class ConstraintBuilder : IResolveConstraint
+ {
+ #region Nested Operator Stack Class
+
+ /// <summary>
+ /// OperatorStack is a type-safe stack for holding ConstraintOperators
+ /// </summary>
+ public class OperatorStack
+ {
+ private readonly Stack<ConstraintOperator> stack = new Stack<ConstraintOperator>();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OperatorStack"/> class.
+ /// </summary>
+ /// <param name="builder">The ConstraintBuilder using this stack.</param>
+ public OperatorStack(ConstraintBuilder builder)
+ {
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this <see cref="OperatorStack"/> is empty.
+ /// </summary>
+ /// <value><c>true</c> if empty; otherwise, <c>false</c>.</value>
+ public bool Empty
+ {
+ get { return stack.Count == 0; }
+ }
+
+ /// <summary>
+ /// Gets the topmost operator without modifying the stack.
+ /// </summary>
+ public ConstraintOperator Top
+ {
+ get { return stack.Peek(); }
+ }
+
+ /// <summary>
+ /// Pushes the specified operator onto the stack.
+ /// </summary>
+ /// <param name="op">The operator to put onto the stack.</param>
+ public void Push(ConstraintOperator op)
+ {
+ stack.Push(op);
+ }
+
+ /// <summary>
+ /// Pops the topmost operator from the stack.
+ /// </summary>
+ /// <returns>The topmost operator on the stack</returns>
+ public ConstraintOperator Pop()
+ {
+ return stack.Pop();
+ }
+ }
+
+ #endregion
+
+ #region Nested Constraint Stack Class
+
+ /// <summary>
+ /// ConstraintStack is a type-safe stack for holding Constraints
+ /// </summary>
+ public class ConstraintStack
+ {
+ private readonly Stack<IConstraint> stack = new Stack<IConstraint>();
+ private readonly ConstraintBuilder builder;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConstraintStack"/> class.
+ /// </summary>
+ /// <param name="builder">The ConstraintBuilder using this stack.</param>
+ public ConstraintStack(ConstraintBuilder builder)
+ {
+ this.builder = builder;
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this <see cref="ConstraintStack"/> is empty.
+ /// </summary>
+ /// <value><c>true</c> if empty; otherwise, <c>false</c>.</value>
+ public bool Empty
+ {
+ get { return stack.Count == 0; }
+ }
+
+ /// <summary>
+ /// Pushes the specified constraint. As a side effect,
+ /// the constraint's Builder field is set to the
+ /// ConstraintBuilder owning this stack.
+ /// </summary>
+ /// <param name="constraint">The constraint to put onto the stack</param>
+ public void Push(IConstraint constraint)
+ {
+ stack.Push(constraint);
+ constraint.Builder = this.builder;
+ }
+
+ /// <summary>
+ /// Pops this topmost constraint from the stack.
+ /// As a side effect, the constraint's Builder
+ /// field is set to null.
+ /// </summary>
+ /// <returns>The topmost contraint on the stack</returns>
+ public IConstraint Pop()
+ {
+ IConstraint constraint = stack.Pop();
+ constraint.Builder = null;
+ return constraint;
+ }
+ }
+
+ #endregion
+
+ #region Instance Fields
+
+ private readonly OperatorStack ops;
+
+ private readonly ConstraintStack constraints;
+
+ private object lastPushed;
+
+ #endregion
+
+ #region Constructor
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConstraintBuilder"/> class.
+ /// </summary>
+ public ConstraintBuilder()
+ {
+ this.ops = new OperatorStack(this);
+ this.constraints = new ConstraintStack(this);
+ }
+
+ #endregion
+
+ #region Public Methods
+
+ /// <summary>
+ /// Appends the specified operator to the expression by first
+ /// reducing the operator stack and then pushing the new
+ /// operator on the stack.
+ /// </summary>
+ /// <param name="op">The operator to push.</param>
+ public void Append(ConstraintOperator op)
+ {
+ op.LeftContext = lastPushed;
+ if (lastPushed is ConstraintOperator)
+ SetTopOperatorRightContext(op);
+
+ // Reduce any lower precedence operators
+ ReduceOperatorStack(op.LeftPrecedence);
+
+ ops.Push(op);
+ lastPushed = op;
+ }
+
+ /// <summary>
+ /// Appends the specified constraint to the expression by pushing
+ /// it on the constraint stack.
+ /// </summary>
+ /// <param name="constraint">The constraint to push.</param>
+ public void Append(Constraint constraint)
+ {
+ if (lastPushed is ConstraintOperator)
+ SetTopOperatorRightContext(constraint);
+
+ constraints.Push(constraint);
+ lastPushed = constraint;
+ constraint.Builder = this;
+ }
+
+ /// <summary>
+ /// Sets the top operator right context.
+ /// </summary>
+ /// <param name="rightContext">The right context.</param>
+ private void SetTopOperatorRightContext(object rightContext)
+ {
+ // Some operators change their precedence based on
+ // the right context - save current precedence.
+ int oldPrecedence = ops.Top.LeftPrecedence;
+
+ ops.Top.RightContext = rightContext;
+
+ // If the precedence increased, we may be able to
+ // reduce the region of the stack below the operator
+ if (ops.Top.LeftPrecedence > oldPrecedence)
+ {
+ ConstraintOperator changedOp = ops.Pop();
+ ReduceOperatorStack(changedOp.LeftPrecedence);
+ ops.Push(changedOp);
+ }
+ }
+
+ /// <summary>
+ /// Reduces the operator stack until the topmost item
+ /// precedence is greater than or equal to the target precedence.
+ /// </summary>
+ /// <param name="targetPrecedence">The target precedence.</param>
+ private void ReduceOperatorStack(int targetPrecedence)
+ {
+ while (!ops.Empty && ops.Top.RightPrecedence < targetPrecedence)
+ ops.Pop().Reduce(constraints);
+ }
+
+ #endregion
+
+ #region IResolveConstraint Implementation
+
+ /// <summary>
+ /// Resolves this instance, returning a Constraint. If the Builder
+ /// is not currently in a resolvable state, an exception is thrown.
+ /// </summary>
+ /// <returns>The resolved constraint</returns>
+ public IConstraint Resolve()
+ {
+ if (!IsResolvable)
+ throw new InvalidOperationException("A partial expression may not be resolved");
+
+ while (!ops.Empty)
+ {
+ ConstraintOperator op = ops.Pop();
+ op.Reduce(constraints);
+ }
+
+ return constraints.Pop();
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ /// <summary>
+ /// Gets a value indicating whether this instance is resolvable.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if this instance is resolvable; otherwise, <c>false</c>.
+ /// </value>
+ private bool IsResolvable
+ {
+ get { return lastPushed is Constraint || lastPushed is SelfResolvingOperator; }
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Runtime.CompilerServices;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// ConstraintExpression represents a compound constraint in the
+ /// process of being constructed from a series of syntactic elements.
+ ///
+ /// Individual elements are appended to the expression as they are
+ /// reorganized. When a constraint is appended, it is returned as the
+ /// value of the operation so that modifiers may be applied. However,
+ /// any partially built expression is attached to the constraint for
+ /// later resolution. When an operator is appended, the partial
+ /// expression is returned. If it's a self-resolving operator, then
+ /// a ResolvableConstraintExpression is returned.
+ /// </summary>
+ public class ConstraintExpression
+ {
+ #region Instance Fields
+
+ /// <summary>
+ /// The ConstraintBuilder holding the elements recognized so far
+ /// </summary>
+ protected ConstraintBuilder builder;
+
+ #endregion
+
+ #region Constructors
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConstraintExpression"/> class.
+ /// </summary>
+ public ConstraintExpression()
+ {
+ this.builder = new ConstraintBuilder();
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConstraintExpression"/>
+ /// class passing in a ConstraintBuilder, which may be pre-populated.
+ /// </summary>
+ /// <param name="builder">The builder.</param>
+ public ConstraintExpression(ConstraintBuilder builder)
+ {
+ this.builder = builder;
+ }
+
+ #endregion
+
+ #region ToString()
+
+ /// <summary>
+ /// Returns a string representation of the expression as it
+ /// currently stands. This should only be used for testing,
+ /// since it has the side-effect of resolving the expression.
+ /// </summary>
+ /// <returns></returns>
+ public override string ToString()
+ {
+ return builder.Resolve().ToString();
+ }
+
+ #endregion
+
+ #region Append Methods
+
+ /// <summary>
+ /// Appends an operator to the expression and returns the
+ /// resulting expression itself.
+ /// </summary>
+ public ConstraintExpression Append(ConstraintOperator op)
+ {
+ builder.Append(op);
+ return this;
+ }
+
+ /// <summary>
+ /// Appends a self-resolving operator to the expression and
+ /// returns a new ResolvableConstraintExpression.
+ /// </summary>
+ public ResolvableConstraintExpression Append(SelfResolvingOperator op)
+ {
+ builder.Append(op);
+ return new ResolvableConstraintExpression(builder);
+ }
+
+ /// <summary>
+ /// Appends a constraint to the expression and returns that
+ /// constraint, which is associated with the current state
+ /// of the expression being built. Note that the constraint
+ /// is not reduced at this time. For example, if there
+ /// is a NotOperator on the stack we don't reduce and
+ /// return a NotConstraint. The original constraint must
+ /// be returned because it may support modifiers that
+ /// are yet to be applied.
+ /// </summary>
+ public Constraint Append(Constraint constraint)
+ {
+ builder.Append(constraint);
+ return constraint;
+ }
+
+ #endregion
+
+ #region Not
+
+ /// <summary>
+ /// Returns a ConstraintExpression that negates any
+ /// following constraint.
+ /// </summary>
+ public ConstraintExpression Not
+ {
+ get { return this.Append(new NotOperator()); }
+ }
+
+ /// <summary>
+ /// Returns a ConstraintExpression that negates any
+ /// following constraint.
+ /// </summary>
+ public ConstraintExpression No
+ {
+ get { return this.Append(new NotOperator()); }
+ }
+
+ #endregion
+
+ #region All
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding if all of them succeed.
+ /// </summary>
+ public ConstraintExpression All
+ {
+ get { return this.Append(new AllOperator()); }
+ }
+
+ #endregion
+
+ #region Some
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding if at least one of them succeeds.
+ /// </summary>
+ public ConstraintExpression Some
+ {
+ get { return this.Append(new SomeOperator()); }
+ }
+
+ #endregion
+
+ #region None
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding if all of them fail.
+ /// </summary>
+ public ConstraintExpression None
+ {
+ get { return this.Append(new NoneOperator()); }
+ }
+
+ #endregion
+
+ #region Exactly(n)
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding only if a specified number of them succeed.
+ /// </summary>
+ public ConstraintExpression Exactly(int expectedCount)
+ {
+ return this.Append(new ExactCountOperator(expectedCount));
+ }
+
+ #endregion
+
+ #region Property
+
+ /// <summary>
+ /// Returns a new PropertyConstraintExpression, which will either
+ /// test for the existence of the named property on the object
+ /// being tested or apply any following constraint to that property.
+ /// </summary>
+ public ResolvableConstraintExpression Property(string name)
+ {
+ return this.Append(new PropOperator(name));
+ }
+
+ #endregion
+
+ #region Length
+
+ /// <summary>
+ /// Returns a new ConstraintExpression, which will apply the following
+ /// constraint to the Length property of the object being tested.
+ /// </summary>
+ public ResolvableConstraintExpression Length
+ {
+ get { return Property("Length"); }
+ }
+
+ #endregion
+
+ #region Count
+
+ /// <summary>
+ /// Returns a new ConstraintExpression, which will apply the following
+ /// constraint to the Count property of the object being tested.
+ /// </summary>
+ public ResolvableConstraintExpression Count
+ {
+ get { return Property("Count"); }
+ }
+
+ #endregion
+
+ #region Message
+
+ /// <summary>
+ /// Returns a new ConstraintExpression, which will apply the following
+ /// constraint to the Message property of the object being tested.
+ /// </summary>
+ public ResolvableConstraintExpression Message
+ {
+ get { return Property("Message"); }
+ }
+
+ #endregion
+
+ #region InnerException
+
+ /// <summary>
+ /// Returns a new ConstraintExpression, which will apply the following
+ /// constraint to the InnerException property of the object being tested.
+ /// </summary>
+ public ResolvableConstraintExpression InnerException
+ {
+ get { return Property("InnerException"); }
+ }
+
+ #endregion
+
+ #region Attribute
+
+ /// <summary>
+ /// Returns a new AttributeConstraint checking for the
+ /// presence of a particular attribute on an object.
+ /// </summary>
+ public ResolvableConstraintExpression Attribute(Type expectedType)
+ {
+ return this.Append(new AttributeOperator(expectedType));
+ }
+
+ /// <summary>
+ /// Returns a new AttributeConstraint checking for the
+ /// presence of a particular attribute on an object.
+ /// </summary>
+ public ResolvableConstraintExpression Attribute<TExpected>()
+ {
+ return Attribute(typeof(TExpected));
+ }
+
+ #endregion
+
+ #region With
+
+ /// <summary>
+ /// With is currently a NOP - reserved for future use.
+ /// </summary>
+ public ConstraintExpression With
+ {
+ get { return this.Append(new WithOperator()); }
+ }
+
+ #endregion
+
+ #region Matches
+
+ /// <summary>
+ /// Returns the constraint provided as an argument - used to allow custom
+ /// custom constraints to easily participate in the syntax.
+ /// </summary>
+ public Constraint Matches(IResolveConstraint constraint)
+ {
+ return this.Append((Constraint)constraint.Resolve());
+ }
+
+ /// <summary>
+ /// Returns the constraint provided as an argument - used to allow custom
+ /// custom constraints to easily participate in the syntax.
+ /// </summary>
+ public Constraint Matches<TActual>(Predicate<TActual> predicate)
+ {
+ return this.Append(new PredicateConstraint<TActual>(predicate));
+ }
+
+ #endregion
+
+ #region Null
+
+ /// <summary>
+ /// Returns a constraint that tests for null
+ /// </summary>
+ public NullConstraint Null
+ {
+ get { return (NullConstraint)this.Append(new NullConstraint()); }
+ }
+
+ #endregion
+
+ #region True
+
+ /// <summary>
+ /// Returns a constraint that tests for True
+ /// </summary>
+ public TrueConstraint True
+ {
+ get { return (TrueConstraint)this.Append(new TrueConstraint()); }
+ }
+
+ #endregion
+
+ #region False
+
+ /// <summary>
+ /// Returns a constraint that tests for False
+ /// </summary>
+ public FalseConstraint False
+ {
+ get { return (FalseConstraint)this.Append(new FalseConstraint()); }
+ }
+
+ #endregion
+
+ #region Positive
+
+ /// <summary>
+ /// Returns a constraint that tests for a positive value
+ /// </summary>
+ public GreaterThanConstraint Positive
+ {
+ get { return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(0)); }
+ }
+
+ #endregion
+
+ #region Negative
+
+ /// <summary>
+ /// Returns a constraint that tests for a negative value
+ /// </summary>
+ public LessThanConstraint Negative
+ {
+ get { return (LessThanConstraint)this.Append(new LessThanConstraint(0)); }
+ }
+
+ #endregion
+
+ #region Zero
+
+ /// <summary>
+ /// Returns a constraint that tests if item is equal to zero
+ /// </summary>
+ public EqualConstraint Zero
+ {
+ get { return (EqualConstraint)this.Append(new EqualConstraint(0)); }
+ }
+
+ #endregion
+
+ #region NaN
+
+ /// <summary>
+ /// Returns a constraint that tests for NaN
+ /// </summary>
+ public NaNConstraint NaN
+ {
+ get { return (NaNConstraint)this.Append(new NaNConstraint()); }
+ }
+
+ #endregion
+
+ #region Empty
+
+ /// <summary>
+ /// Returns a constraint that tests for empty
+ /// </summary>
+ public EmptyConstraint Empty
+ {
+ get { return (EmptyConstraint)this.Append(new EmptyConstraint()); }
+ }
+
+ #endregion
+
+ #region Unique
+
+ /// <summary>
+ /// Returns a constraint that tests whether a collection
+ /// contains all unique items.
+ /// </summary>
+ public UniqueItemsConstraint Unique
+ {
+ get { return (UniqueItemsConstraint)this.Append(new UniqueItemsConstraint()); }
+ }
+
+ #endregion
+
+ #region BinarySerializable
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Returns a constraint that tests whether an object graph is serializable in binary format.
+ /// </summary>
+ public BinarySerializableConstraint BinarySerializable
+ {
+ get { return (BinarySerializableConstraint)this.Append(new BinarySerializableConstraint()); }
+ }
+#endif
+
+ #endregion
+
+ #region XmlSerializable
+
+#if !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Returns a constraint that tests whether an object graph is serializable in xml format.
+ /// </summary>
+ public XmlSerializableConstraint XmlSerializable
+ {
+ get { return (XmlSerializableConstraint)this.Append(new XmlSerializableConstraint()); }
+ }
+#endif
+
+ #endregion
+
+ #region EqualTo
+
+ /// <summary>
+ /// Returns a constraint that tests two items for equality
+ /// </summary>
+ public EqualConstraint EqualTo(object expected)
+ {
+ return (EqualConstraint)this.Append(new EqualConstraint(expected));
+ }
+
+ #endregion
+
+ #region SameAs
+
+ /// <summary>
+ /// Returns a constraint that tests that two references are the same object
+ /// </summary>
+ public SameAsConstraint SameAs(object expected)
+ {
+ return (SameAsConstraint)this.Append(new SameAsConstraint(expected));
+ }
+
+ #endregion
+
+ #region GreaterThan
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is greater than the supplied argument
+ /// </summary>
+ public GreaterThanConstraint GreaterThan(object expected)
+ {
+ return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(expected));
+ }
+
+ #endregion
+
+ #region GreaterThanOrEqualTo
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is greater than or equal to the supplied argument
+ /// </summary>
+ public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
+ {
+ return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected));
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is greater than or equal to the supplied argument
+ /// </summary>
+ public GreaterThanOrEqualConstraint AtLeast(object expected)
+ {
+ return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected));
+ }
+
+ #endregion
+
+ #region LessThan
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is less than the supplied argument
+ /// </summary>
+ public LessThanConstraint LessThan(object expected)
+ {
+ return (LessThanConstraint)this.Append(new LessThanConstraint(expected));
+ }
+
+ #endregion
+
+ #region LessThanOrEqualTo
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is less than or equal to the supplied argument
+ /// </summary>
+ public LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
+ {
+ return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected));
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is less than or equal to the supplied argument
+ /// </summary>
+ public LessThanOrEqualConstraint AtMost(object expected)
+ {
+ return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected));
+ }
+
+ #endregion
+
+ #region TypeOf
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual
+ /// value is of the exact type supplied as an argument.
+ /// </summary>
+ public ExactTypeConstraint TypeOf(Type expectedType)
+ {
+ return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(expectedType));
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual
+ /// value is of the exact type supplied as an argument.
+ /// </summary>
+ public ExactTypeConstraint TypeOf<TExpected>()
+ {
+ return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(typeof(TExpected)));
+ }
+
+ #endregion
+
+ #region InstanceOf
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is of the type supplied as an argument or a derived type.
+ /// </summary>
+ public InstanceOfTypeConstraint InstanceOf(Type expectedType)
+ {
+ return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(expectedType));
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is of the type supplied as an argument or a derived type.
+ /// </summary>
+ public InstanceOfTypeConstraint InstanceOf<TExpected>()
+ {
+ return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(typeof(TExpected)));
+ }
+
+ #endregion
+
+ #region AssignableFrom
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is assignable from the type supplied as an argument.
+ /// </summary>
+ public AssignableFromConstraint AssignableFrom(Type expectedType)
+ {
+ return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(expectedType));
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is assignable from the type supplied as an argument.
+ /// </summary>
+ public AssignableFromConstraint AssignableFrom<TExpected>()
+ {
+ return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(typeof(TExpected)));
+ }
+
+ #endregion
+
+ #region AssignableTo
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is assignable from the type supplied as an argument.
+ /// </summary>
+ public AssignableToConstraint AssignableTo(Type expectedType)
+ {
+ return (AssignableToConstraint)this.Append(new AssignableToConstraint(expectedType));
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is assignable from the type supplied as an argument.
+ /// </summary>
+ public AssignableToConstraint AssignableTo<TExpected>()
+ {
+ return (AssignableToConstraint)this.Append(new AssignableToConstraint(typeof(TExpected)));
+ }
+
+ #endregion
+
+ #region EquivalentTo
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is a collection containing the same elements as the
+ /// collection supplied as an argument.
+ /// </summary>
+ public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
+ {
+ return (CollectionEquivalentConstraint)this.Append(new CollectionEquivalentConstraint(expected));
+ }
+
+ #endregion
+
+ #region SubsetOf
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is a subset of the collection supplied as an argument.
+ /// </summary>
+ public CollectionSubsetConstraint SubsetOf(IEnumerable expected)
+ {
+ return (CollectionSubsetConstraint)this.Append(new CollectionSubsetConstraint(expected));
+ }
+
+ #endregion
+
+ #region SupersetOf
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is a superset of the collection supplied as an argument.
+ /// </summary>
+ public CollectionSupersetConstraint SupersetOf(IEnumerable expected)
+ {
+ return (CollectionSupersetConstraint)this.Append(new CollectionSupersetConstraint(expected));
+ }
+
+ #endregion
+
+ #region Ordered
+
+ /// <summary>
+ /// Returns a constraint that tests whether a collection is ordered
+ /// </summary>
+ public CollectionOrderedConstraint Ordered
+ {
+ get { return (CollectionOrderedConstraint)this.Append(new CollectionOrderedConstraint()); }
+ }
+
+ #endregion
+
+ #region Member
+
+ /// <summary>
+ /// Returns a new CollectionContainsConstraint checking for the
+ /// presence of a particular object in the collection.
+ /// </summary>
+ public CollectionContainsConstraint Member(object expected)
+ {
+ return (CollectionContainsConstraint)this.Append(new CollectionContainsConstraint(expected));
+ }
+
+ #endregion
+
+ #region Contains
+
+ /// <summary>
+ /// Returns a new CollectionContainsConstraint checking for the
+ /// presence of a particular object in the collection.
+ /// </summary>
+ public CollectionContainsConstraint Contains(object expected)
+ {
+ return (CollectionContainsConstraint)this.Append(new CollectionContainsConstraint(expected));
+ }
+
+ /// <summary>
+ /// Returns a new ContainsConstraint. This constraint
+ /// will, in turn, make use of the appropriate second-level
+ /// constraint, depending on the type of the actual argument.
+ /// This overload is only used if the item sought is a string,
+ /// since any other type implies that we are looking for a
+ /// collection member.
+ /// </summary>
+ public ContainsConstraint Contains(string expected)
+ {
+ return (ContainsConstraint)this.Append(new ContainsConstraint(expected));
+ }
+
+ /// <summary>
+ /// Returns a new ContainsConstraint. This constraint
+ /// will, in turn, make use of the appropriate second-level
+ /// constraint, depending on the type of the actual argument.
+ /// This overload is only used if the item sought is a string,
+ /// since any other type implies that we are looking for a
+ /// collection member.
+ /// </summary>
+ public ContainsConstraint Contain(string expected)
+ {
+ return (ContainsConstraint)this.Append(new ContainsConstraint(expected));
+ }
+
+ #endregion
+
+ #region StringContaining
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value contains the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Contains")]
+ public SubstringConstraint StringContaining(string expected)
+ {
+ return (SubstringConstraint)this.Append(new SubstringConstraint(expected));
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value contains the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Contains")]
+ public SubstringConstraint ContainsSubstring(string expected)
+ {
+ return (SubstringConstraint)this.Append(new SubstringConstraint(expected));
+ }
+
+ #endregion
+
+ #region StartsWith
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value starts with the substring supplied as an argument.
+ /// </summary>
+ public StartsWithConstraint StartWith(string expected)
+ {
+ return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected));
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value starts with the substring supplied as an argument.
+ /// </summary>
+ public StartsWithConstraint StartsWith(string expected)
+ {
+ return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected));
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value starts with the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.StartWith or StartsWith")]
+ public StartsWithConstraint StringStarting(string expected)
+ {
+ return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected));
+ }
+
+ #endregion
+
+ #region EndsWith
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value ends with the substring supplied as an argument.
+ /// </summary>
+ public EndsWithConstraint EndWith(string expected)
+ {
+ return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected));
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value ends with the substring supplied as an argument.
+ /// </summary>
+ public EndsWithConstraint EndsWith(string expected)
+ {
+ return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected));
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value ends with the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.EndWith or EndsWith")]
+ public EndsWithConstraint StringEnding(string expected)
+ {
+ return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected));
+ }
+
+ #endregion
+
+ #region Matches
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value matches the regular expression supplied as an argument.
+ /// </summary>
+ public RegexConstraint Match(string pattern)
+ {
+ return (RegexConstraint)this.Append(new RegexConstraint(pattern));
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value matches the regular expression supplied as an argument.
+ /// </summary>
+ public RegexConstraint Matches(string pattern)
+ {
+ return (RegexConstraint)this.Append(new RegexConstraint(pattern));
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value matches the regular expression supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.Match or Matches")]
+ public RegexConstraint StringMatching(string pattern)
+ {
+ return (RegexConstraint)this.Append(new RegexConstraint(pattern));
+ }
+
+ #endregion
+
+#if !PORTABLE
+ #region SamePath
+
+ /// <summary>
+ /// Returns a constraint that tests whether the path provided
+ /// is the same as an expected path after canonicalization.
+ /// </summary>
+ public SamePathConstraint SamePath(string expected)
+ {
+ return (SamePathConstraint)this.Append(new SamePathConstraint(expected));
+ }
+
+ #endregion
+
+ #region SubPath
+
+ /// <summary>
+ /// Returns a constraint that tests whether the path provided
+ /// is the a subpath of the expected path after canonicalization.
+ /// </summary>
+ public SubPathConstraint SubPathOf(string expected)
+ {
+ return (SubPathConstraint)this.Append(new SubPathConstraint(expected));
+ }
+
+ #endregion
+
+ #region SamePathOrUnder
+
+ /// <summary>
+ /// Returns a constraint that tests whether the path provided
+ /// is the same path or under an expected path after canonicalization.
+ /// </summary>
+ public SamePathOrUnderConstraint SamePathOrUnder(string expected)
+ {
+ return (SamePathOrUnderConstraint)this.Append(new SamePathOrUnderConstraint(expected));
+ }
+
+ #endregion
+#endif
+
+ #region InRange
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value falls
+ /// within a specified range.
+ /// </summary>
+ public RangeConstraint InRange(IComparable from, IComparable to)
+ {
+ return (RangeConstraint)this.Append(new RangeConstraint(from, to));
+ }
+
+ #endregion
+
+ #region Exist
+
+#if !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Returns a constraint that succeeds if the value
+ /// is a file or directory and it exists.
+ /// </summary>
+ public Constraint Exist
+ {
+ get { return Append(new FileOrDirectoryExistsConstraint()); }
+ }
+#endif
+
+ #endregion
+
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Helper class with properties and methods that supply
+ /// a number of constraints used in Asserts.
+ /// </summary>
+ public class ConstraintFactory
+ {
+ #region Not
+
+ /// <summary>
+ /// Returns a ConstraintExpression that negates any
+ /// following constraint.
+ /// </summary>
+ public ConstraintExpression Not
+ {
+ get { return Is.Not; }
+ }
+
+ /// <summary>
+ /// Returns a ConstraintExpression that negates any
+ /// following constraint.
+ /// </summary>
+ public ConstraintExpression No
+ {
+ get { return Has.No; }
+ }
+
+ #endregion
+
+ #region All
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding if all of them succeed.
+ /// </summary>
+ public ConstraintExpression All
+ {
+ get { return Is.All; }
+ }
+
+ #endregion
+
+ #region Some
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding if at least one of them succeeds.
+ /// </summary>
+ public ConstraintExpression Some
+ {
+ get { return Has.Some; }
+ }
+
+ #endregion
+
+ #region None
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding if all of them fail.
+ /// </summary>
+ public ConstraintExpression None
+ {
+ get { return Has.None; }
+ }
+
+ #endregion
+
+ #region Exactly(n)
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding only if a specified number of them succeed.
+ /// </summary>
+ public static ConstraintExpression Exactly(int expectedCount)
+ {
+ return Has.Exactly(expectedCount);
+ }
+
+ #endregion
+
+ #region Property
+
+ /// <summary>
+ /// Returns a new PropertyConstraintExpression, which will either
+ /// test for the existence of the named property on the object
+ /// being tested or apply any following constraint to that property.
+ /// </summary>
+ public ResolvableConstraintExpression Property(string name)
+ {
+ return Has.Property(name);
+ }
+
+ #endregion
+
+ #region Length
+
+ /// <summary>
+ /// Returns a new ConstraintExpression, which will apply the following
+ /// constraint to the Length property of the object being tested.
+ /// </summary>
+ public ResolvableConstraintExpression Length
+ {
+ get { return Has.Length; }
+ }
+
+ #endregion
+
+ #region Count
+
+ /// <summary>
+ /// Returns a new ConstraintExpression, which will apply the following
+ /// constraint to the Count property of the object being tested.
+ /// </summary>
+ public ResolvableConstraintExpression Count
+ {
+ get { return Has.Count; }
+ }
+
+ #endregion
+
+ #region Message
+
+ /// <summary>
+ /// Returns a new ConstraintExpression, which will apply the following
+ /// constraint to the Message property of the object being tested.
+ /// </summary>
+ public ResolvableConstraintExpression Message
+ {
+ get { return Has.Message; }
+ }
+
+ #endregion
+
+ #region InnerException
+
+ /// <summary>
+ /// Returns a new ConstraintExpression, which will apply the following
+ /// constraint to the InnerException property of the object being tested.
+ /// </summary>
+ public ResolvableConstraintExpression InnerException
+ {
+ get { return Has.InnerException; }
+ }
+
+ #endregion
+
+ #region Attribute
+
+ /// <summary>
+ /// Returns a new AttributeConstraint checking for the
+ /// presence of a particular attribute on an object.
+ /// </summary>
+ public ResolvableConstraintExpression Attribute(Type expectedType)
+ {
+ return Has.Attribute(expectedType);
+ }
+
+ /// <summary>
+ /// Returns a new AttributeConstraint checking for the
+ /// presence of a particular attribute on an object.
+ /// </summary>
+ public ResolvableConstraintExpression Attribute<TExpected>()
+ {
+ return Attribute(typeof(TExpected));
+ }
+
+ #endregion
+
+ #region Null
+
+ /// <summary>
+ /// Returns a constraint that tests for null
+ /// </summary>
+ public NullConstraint Null
+ {
+ get { return new NullConstraint(); }
+ }
+
+ #endregion
+
+ #region True
+
+ /// <summary>
+ /// Returns a constraint that tests for True
+ /// </summary>
+ public TrueConstraint True
+ {
+ get { return new TrueConstraint(); }
+ }
+
+ #endregion
+
+ #region False
+
+ /// <summary>
+ /// Returns a constraint that tests for False
+ /// </summary>
+ public FalseConstraint False
+ {
+ get { return new FalseConstraint(); }
+ }
+
+ #endregion
+
+ #region Positive
+
+ /// <summary>
+ /// Returns a constraint that tests for a positive value
+ /// </summary>
+ public GreaterThanConstraint Positive
+ {
+ get { return new GreaterThanConstraint(0); }
+ }
+
+ #endregion
+
+ #region Negative
+
+ /// <summary>
+ /// Returns a constraint that tests for a negative value
+ /// </summary>
+ public LessThanConstraint Negative
+ {
+ get { return new LessThanConstraint(0); }
+ }
+
+ #endregion
+
+ #region Zero
+
+ /// <summary>
+ /// Returns a constraint that tests for equality with zero
+ /// </summary>
+ public EqualConstraint Zero
+ {
+ get { return new EqualConstraint(0); }
+ }
+
+ #endregion
+
+ #region NaN
+
+ /// <summary>
+ /// Returns a constraint that tests for NaN
+ /// </summary>
+ public NaNConstraint NaN
+ {
+ get { return new NaNConstraint(); }
+ }
+
+ #endregion
+
+ #region Empty
+
+ /// <summary>
+ /// Returns a constraint that tests for empty
+ /// </summary>
+ public EmptyConstraint Empty
+ {
+ get { return new EmptyConstraint(); }
+ }
+
+ #endregion
+
+ #region Unique
+
+ /// <summary>
+ /// Returns a constraint that tests whether a collection
+ /// contains all unique items.
+ /// </summary>
+ public UniqueItemsConstraint Unique
+ {
+ get { return new UniqueItemsConstraint(); }
+ }
+
+ #endregion
+
+ #region BinarySerializable
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Returns a constraint that tests whether an object graph is serializable in binary format.
+ /// </summary>
+ public BinarySerializableConstraint BinarySerializable
+ {
+ get { return new BinarySerializableConstraint(); }
+ }
+#endif
+
+ #endregion
+
+ #region XmlSerializable
+
+#if !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Returns a constraint that tests whether an object graph is serializable in xml format.
+ /// </summary>
+ public XmlSerializableConstraint XmlSerializable
+ {
+ get { return new XmlSerializableConstraint(); }
+ }
+#endif
+
+ #endregion
+
+ #region EqualTo
+
+ /// <summary>
+ /// Returns a constraint that tests two items for equality
+ /// </summary>
+ public EqualConstraint EqualTo(object expected)
+ {
+ return new EqualConstraint(expected);
+ }
+
+ #endregion
+
+ #region SameAs
+
+ /// <summary>
+ /// Returns a constraint that tests that two references are the same object
+ /// </summary>
+ public SameAsConstraint SameAs(object expected)
+ {
+ return new SameAsConstraint(expected);
+ }
+
+ #endregion
+
+ #region GreaterThan
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is greater than the supplied argument
+ /// </summary>
+ public GreaterThanConstraint GreaterThan(object expected)
+ {
+ return new GreaterThanConstraint(expected);
+ }
+
+ #endregion
+
+ #region GreaterThanOrEqualTo
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is greater than or equal to the supplied argument
+ /// </summary>
+ public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
+ {
+ return new GreaterThanOrEqualConstraint(expected);
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is greater than or equal to the supplied argument
+ /// </summary>
+ public GreaterThanOrEqualConstraint AtLeast(object expected)
+ {
+ return new GreaterThanOrEqualConstraint(expected);
+ }
+
+ #endregion
+
+ #region LessThan
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is less than the supplied argument
+ /// </summary>
+ public LessThanConstraint LessThan(object expected)
+ {
+ return new LessThanConstraint(expected);
+ }
+
+ #endregion
+
+ #region LessThanOrEqualTo
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is less than or equal to the supplied argument
+ /// </summary>
+ public LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
+ {
+ return new LessThanOrEqualConstraint(expected);
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is less than or equal to the supplied argument
+ /// </summary>
+ public LessThanOrEqualConstraint AtMost(object expected)
+ {
+ return new LessThanOrEqualConstraint(expected);
+ }
+
+ #endregion
+
+ #region TypeOf
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual
+ /// value is of the exact type supplied as an argument.
+ /// </summary>
+ public ExactTypeConstraint TypeOf(Type expectedType)
+ {
+ return new ExactTypeConstraint(expectedType);
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual
+ /// value is of the exact type supplied as an argument.
+ /// </summary>
+ public ExactTypeConstraint TypeOf<TExpected>()
+ {
+ return new ExactTypeConstraint(typeof(TExpected));
+ }
+
+ #endregion
+
+ #region InstanceOf
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is of the type supplied as an argument or a derived type.
+ /// </summary>
+ public InstanceOfTypeConstraint InstanceOf(Type expectedType)
+ {
+ return new InstanceOfTypeConstraint(expectedType);
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is of the type supplied as an argument or a derived type.
+ /// </summary>
+ public InstanceOfTypeConstraint InstanceOf<TExpected>()
+ {
+ return new InstanceOfTypeConstraint(typeof(TExpected));
+ }
+
+ #endregion
+
+ #region AssignableFrom
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is assignable from the type supplied as an argument.
+ /// </summary>
+ public AssignableFromConstraint AssignableFrom(Type expectedType)
+ {
+ return new AssignableFromConstraint(expectedType);
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is assignable from the type supplied as an argument.
+ /// </summary>
+ public AssignableFromConstraint AssignableFrom<TExpected>()
+ {
+ return new AssignableFromConstraint(typeof(TExpected));
+ }
+
+ #endregion
+
+ #region AssignableTo
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is assignable from the type supplied as an argument.
+ /// </summary>
+ public AssignableToConstraint AssignableTo(Type expectedType)
+ {
+ return new AssignableToConstraint(expectedType);
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is assignable from the type supplied as an argument.
+ /// </summary>
+ public AssignableToConstraint AssignableTo<TExpected>()
+ {
+ return new AssignableToConstraint(typeof(TExpected));
+ }
+
+ #endregion
+
+ #region EquivalentTo
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is a collection containing the same elements as the
+ /// collection supplied as an argument.
+ /// </summary>
+ public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
+ {
+ return new CollectionEquivalentConstraint(expected);
+ }
+
+ #endregion
+
+ #region SubsetOf
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is a subset of the collection supplied as an argument.
+ /// </summary>
+ public CollectionSubsetConstraint SubsetOf(IEnumerable expected)
+ {
+ return new CollectionSubsetConstraint(expected);
+ }
+
+ #endregion
+
+ #region SupersetOf
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is a superset of the collection supplied as an argument.
+ /// </summary>
+ public CollectionSupersetConstraint SupersetOf(IEnumerable expected)
+ {
+ return new CollectionSupersetConstraint(expected);
+ }
+
+ #endregion
+
+ #region Ordered
+
+ /// <summary>
+ /// Returns a constraint that tests whether a collection is ordered
+ /// </summary>
+ public CollectionOrderedConstraint Ordered
+ {
+ get { return new CollectionOrderedConstraint(); }
+ }
+
+ #endregion
+
+ #region Member
+
+ /// <summary>
+ /// Returns a new CollectionContainsConstraint checking for the
+ /// presence of a particular object in the collection.
+ /// </summary>
+ public CollectionContainsConstraint Member(object expected)
+ {
+ return new CollectionContainsConstraint(expected);
+ }
+
+ /// <summary>
+ /// Returns a new CollectionContainsConstraint checking for the
+ /// presence of a particular object in the collection.
+ /// </summary>
+ public CollectionContainsConstraint Contains(object expected)
+ {
+ return new CollectionContainsConstraint(expected);
+ }
+
+ #endregion
+
+ #region Contains
+
+ /// <summary>
+ /// Returns a new ContainsConstraint. This constraint
+ /// will, in turn, make use of the appropriate second-level
+ /// constraint, depending on the type of the actual argument.
+ /// This overload is only used if the item sought is a string,
+ /// since any other type implies that we are looking for a
+ /// collection member.
+ /// </summary>
+ public ContainsConstraint Contains(string expected)
+ {
+ return new ContainsConstraint(expected);
+ }
+
+ #endregion
+
+ #region StringContaining
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value contains the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Contains")]
+ public SubstringConstraint StringContaining(string expected)
+ {
+ return new SubstringConstraint(expected);
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value contains the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Contains")]
+ public SubstringConstraint ContainsSubstring(string expected)
+ {
+ return new SubstringConstraint(expected);
+ }
+
+ #endregion
+
+ #region DoesNotContain
+
+ /// <summary>
+ /// Returns a constraint that fails if the actual
+ /// value contains the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.Not.Contain")]
+ public SubstringConstraint DoesNotContain(string expected)
+ {
+ return new ConstraintExpression().Not.ContainsSubstring(expected);
+ }
+
+ #endregion
+
+ #region StartsWith
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value starts with the substring supplied as an argument.
+ /// </summary>
+ public StartsWithConstraint StartWith(string expected)
+ {
+ return new StartsWithConstraint(expected);
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value starts with the substring supplied as an argument.
+ /// </summary>
+ public StartsWithConstraint StartsWith(string expected)
+ {
+ return new StartsWithConstraint(expected);
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value starts with the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.StartWith or StartsWith")]
+ public StartsWithConstraint StringStarting(string expected)
+ {
+ return new StartsWithConstraint(expected);
+ }
+
+ #endregion
+
+ #region DoesNotStartWith
+
+ /// <summary>
+ /// Returns a constraint that fails if the actual
+ /// value starts with the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.Not.StartWith")]
+ public StartsWithConstraint DoesNotStartWith(string expected)
+ {
+ return new ConstraintExpression().Not.StartsWith(expected);
+ }
+
+ #endregion
+
+ #region EndsWith
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value ends with the substring supplied as an argument.
+ /// </summary>
+ public EndsWithConstraint EndWith(string expected)
+ {
+ return new EndsWithConstraint(expected);
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value ends with the substring supplied as an argument.
+ /// </summary>
+ public EndsWithConstraint EndsWith(string expected)
+ {
+ return new EndsWithConstraint(expected);
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value ends with the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.EndWith or EndsWith")]
+ public EndsWithConstraint StringEnding(string expected)
+ {
+ return new EndsWithConstraint(expected);
+ }
+
+ #endregion
+
+ #region DoesNotEndWith
+
+ /// <summary>
+ /// Returns a constraint that fails if the actual
+ /// value ends with the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.Not.EndWith")]
+ public EndsWithConstraint DoesNotEndWith(string expected)
+ {
+ return new ConstraintExpression().Not.EndsWith(expected);
+ }
+
+ #endregion
+
+ #region Matches
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value matches the regular expression supplied as an argument.
+ /// </summary>
+ public RegexConstraint Match(string pattern)
+ {
+ return new RegexConstraint(pattern);
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value matches the regular expression supplied as an argument.
+ /// </summary>
+ public RegexConstraint Matches(string pattern)
+ {
+ return new RegexConstraint(pattern);
+ }
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value matches the regular expression supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.Match or Matches")]
+ public RegexConstraint StringMatching(string pattern)
+ {
+ return new RegexConstraint(pattern);
+ }
+
+ #endregion
+
+ #region DoesNotMatch
+
+ /// <summary>
+ /// Returns a constraint that fails if the actual
+ /// value matches the pattern supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.Not.Match")]
+ public RegexConstraint DoesNotMatch(string pattern)
+ {
+ return new ConstraintExpression().Not.Matches(pattern);
+ }
+
+ #endregion
+
+#if !PORTABLE
+ #region SamePath
+
+ /// <summary>
+ /// Returns a constraint that tests whether the path provided
+ /// is the same as an expected path after canonicalization.
+ /// </summary>
+ public SamePathConstraint SamePath(string expected)
+ {
+ return new SamePathConstraint(expected);
+ }
+
+ #endregion
+
+ #region SubPath
+
+ /// <summary>
+ /// Returns a constraint that tests whether the path provided
+ /// is a subpath of the expected path after canonicalization.
+ /// </summary>
+ public SubPathConstraint SubPathOf(string expected)
+ {
+ return new SubPathConstraint(expected);
+ }
+
+ #endregion
+
+ #region SamePathOrUnder
+
+ /// <summary>
+ /// Returns a constraint that tests whether the path provided
+ /// is the same path or under an expected path after canonicalization.
+ /// </summary>
+ public SamePathOrUnderConstraint SamePathOrUnder(string expected)
+ {
+ return new SamePathOrUnderConstraint(expected);
+ }
+
+ #endregion
+#endif
+
+ #region InRange
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value falls
+ /// within a specified range.
+ /// </summary>
+ public RangeConstraint InRange(IComparable from, IComparable to)
+ {
+ return new RangeConstraint(from, to);
+ }
+
+ #endregion
+
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// ConstraintStatus represents the status of a ConstraintResult
+ /// returned by a Constraint being applied to an actual value.
+ /// </summary>
+ public enum ConstraintStatus
+ {
+ /// <summary>
+ /// The status has not yet been set
+ /// </summary>
+ Unknown,
+
+ /// <summary>
+ /// The constraint succeeded
+ /// </summary>
+ Success,
+
+ /// <summary>
+ /// The constraint failed
+ /// </summary>
+ Failure,
+
+ /// <summary>
+ /// An error occured in applying the constraint (reserved for future use)
+ /// </summary>
+ Error
+ }
+
+ /// <summary>
+ /// Contain the result of matching a <see cref="Constraint"/> against an actual value.
+ /// </summary>
+ public class ConstraintResult
+ {
+ IConstraint _constraint;
+
+ #region Constructors
+
+ /// <summary>
+ /// Constructs a <see cref="ConstraintResult"/> for a particular <see cref="Constraint"/>.
+ /// </summary>
+ /// <param name="constraint">The Constraint to which this result applies.</param>
+ /// <param name="actualValue">The actual value to which the Constraint was applied.</param>
+ public ConstraintResult(IConstraint constraint, object actualValue)
+ {
+ _constraint = constraint;
+ ActualValue = actualValue;
+ }
+
+ /// <summary>
+ /// Constructs a <see cref="ConstraintResult"/> for a particular <see cref="Constraint"/>.
+ /// </summary>
+ /// <param name="constraint">The Constraint to which this result applies.</param>
+ /// <param name="actualValue">The actual value to which the Constraint was applied.</param>
+ /// <param name="status">The status of the new ConstraintResult.</param>
+ public ConstraintResult(IConstraint constraint, object actualValue, ConstraintStatus status)
+ : this(constraint, actualValue)
+ {
+ Status = status;
+ }
+
+ /// <summary>
+ /// Constructs a <see cref="ConstraintResult"/> for a particular <see cref="Constraint"/>.
+ /// </summary>
+ /// <param name="constraint">The Constraint to which this result applies.</param>
+ /// <param name="actualValue">The actual value to which the Constraint was applied.</param>
+ /// <param name="isSuccess">If true, applies a status of Success to the result, otherwise Failure.</param>
+ public ConstraintResult(IConstraint constraint, object actualValue, bool isSuccess)
+ : this(constraint, actualValue)
+ {
+ Status = isSuccess ? ConstraintStatus.Success : ConstraintStatus.Failure;
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// The actual value that was passed to the <see cref="Constraint.ApplyTo{TActual}(TActual)"/> method.
+ /// </summary>
+ public object ActualValue { get; private set; }
+
+ /// <summary>
+ /// Gets and sets the ResultStatus for this result.
+ /// </summary>
+ public ConstraintStatus Status { get; set; }
+
+ /// <summary>
+ /// True if actual value meets the Constraint criteria otherwise false.
+ /// </summary>
+ public virtual bool IsSuccess
+ {
+ get { return Status == ConstraintStatus.Success; }
+ }
+
+ /// <summary>
+ /// Display friendly name of the constraint.
+ /// </summary>
+ public string Name { get { return _constraint.DisplayName; } }
+
+ /// <summary>
+ /// Description of the constraint may be affected by the state the constraint had
+ /// when <see cref="Constraint.ApplyTo{TActual}(TActual)"/> was performed against the actual value.
+ /// </summary>
+ public string Description { get { return _constraint.Description; } }
+
+ #endregion
+
+ #region Write Methods
+
+ /// <summary>
+ /// Write the failure message to the MessageWriter provided
+ /// as an argument. The default implementation simply passes
+ /// the result and the actual value to the writer, which
+ /// then displays the constraint description and the value.
+ ///
+ /// Constraints that need to provide additional details,
+ /// such as where the error occured can override this.
+ /// </summary>
+ /// <param name="writer">The MessageWriter on which to display the message</param>
+ public virtual void WriteMessageTo(MessageWriter writer)
+ {
+ writer.DisplayDifferences(this);
+ }
+
+ /// <summary>
+ /// Write the actual value for a failing constraint test to a
+ /// MessageWriter. The default implementation simply writes
+ /// the raw value of actual, leaving it to the writer to
+ /// perform any formatting.
+ /// </summary>
+ /// <param name="writer">The writer on which the actual value is displayed</param>
+ public virtual void WriteActualValueTo(MessageWriter writer)
+ {
+ writer.WriteActualValue(ActualValue);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+
+namespace NUnit.Framework.Constraints
+{
+ // TODO Needs tests
+ /// <summary>
+ /// ContainsConstraint tests a whether a string contains a substring
+ /// or a collection contains an object. It postpones the decision of
+ /// which test to use until the type of the actual argument is known.
+ /// This allows testing whether a string is contained in a collection
+ /// or as a substring of another string using the same syntax.
+ /// </summary>
+ public class ContainsConstraint : Constraint
+ {
+ readonly object _expected;
+ Constraint _realConstraint;
+ bool _ignoreCase;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ContainsConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The _expected.</param>
+ public ContainsConstraint(object expected)
+ {
+ this._expected = expected;
+ }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return _realConstraint != null ?
+ _realConstraint.Description :
+ "containing " + MsgUtils.FormatValue(_expected); }
+ }
+
+ /// <summary>
+ /// Flag the constraint to ignore case and return self.
+ /// </summary>
+ public ContainsConstraint IgnoreCase
+ {
+ get { _ignoreCase = true; return this; }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ if (actual is string)
+ {
+ StringConstraint constraint = new SubstringConstraint((string)_expected);
+ if (_ignoreCase)
+ constraint = constraint.IgnoreCase;
+ _realConstraint = constraint;
+ }
+ else
+ _realConstraint = new CollectionContainsConstraint(_expected);
+
+ return _realConstraint.ApplyTo(actual);
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !PORTABLE
+using System;
+using System.Diagnostics;
+using System.Threading;
+using NUnit.Compatibility;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework.Constraints
+{
+ ///<summary>
+ /// Applies a delay to the match so that a match can be evaluated in the future.
+ ///</summary>
+ public class DelayedConstraint : PrefixConstraint
+ {
+ // TODO: Needs error message tests
+
+ private readonly int delayInMilliseconds;
+ private readonly int pollingInterval;
+
+ ///<summary>
+ /// Creates a new DelayedConstraint
+ ///</summary>
+ ///<param name="baseConstraint">The inner constraint to decorate</param>
+ ///<param name="delayInMilliseconds">The time interval after which the match is performed</param>
+ ///<exception cref="InvalidOperationException">If the value of <paramref name="delayInMilliseconds"/> is less than 0</exception>
+ public DelayedConstraint(IConstraint baseConstraint, int delayInMilliseconds)
+ : this(baseConstraint, delayInMilliseconds, 0) { }
+
+ ///<summary>
+ /// Creates a new DelayedConstraint
+ ///</summary>
+ ///<param name="baseConstraint">The inner constraint to decorate</param>
+ ///<param name="delayInMilliseconds">The time interval after which the match is performed, in milliseconds</param>
+ ///<param name="pollingInterval">The time interval used for polling, in milliseconds</param>
+ ///<exception cref="InvalidOperationException">If the value of <paramref name="delayInMilliseconds"/> is less than 0</exception>
+ public DelayedConstraint(IConstraint baseConstraint, int delayInMilliseconds, int pollingInterval)
+ : base(baseConstraint)
+ {
+ if (delayInMilliseconds < 0)
+ throw new ArgumentException("Cannot check a condition in the past", "delayInMilliseconds");
+
+ this.delayInMilliseconds = delayInMilliseconds;
+ this.pollingInterval = pollingInterval;
+ }
+
+ /// <summary>
+ /// Gets text describing a constraint
+ /// </summary>
+ public override string Description
+ {
+ get { return string.Format("{0} after {1} millisecond delay", BaseConstraint.Description, delayInMilliseconds); }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for if the base constraint fails, false if it succeeds</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ long now = Stopwatch.GetTimestamp();
+ long delayEnd = TimestampOffset(now, TimeSpan.FromMilliseconds(delayInMilliseconds));
+
+ if (pollingInterval > 0)
+ {
+ long nextPoll = TimestampOffset(now, TimeSpan.FromMilliseconds(pollingInterval));
+ while ((now = Stopwatch.GetTimestamp()) < delayEnd)
+ {
+ if (nextPoll > now)
+ Thread.Sleep((int)TimestampDiff(delayEnd < nextPoll ? delayEnd : nextPoll, now).TotalMilliseconds);
+ nextPoll = TimestampOffset(now, TimeSpan.FromMilliseconds(pollingInterval));
+
+ ConstraintResult result = BaseConstraint.ApplyTo(actual);
+ if (result.IsSuccess)
+ return new ConstraintResult(this, actual, true);
+ }
+ }
+ if ((now = Stopwatch.GetTimestamp()) < delayEnd)
+ Thread.Sleep((int)TimestampDiff(delayEnd, now).TotalMilliseconds);
+
+ return new ConstraintResult(this, actual, BaseConstraint.ApplyTo(actual).IsSuccess);
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a delegate
+ /// </summary>
+ /// <param name="del">The delegate whose value is to be tested</param>
+ /// <returns>A ConstraintResult</returns>
+ public override ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del)
+ {
+ long now = Stopwatch.GetTimestamp();
+ long delayEnd = TimestampOffset(now, TimeSpan.FromMilliseconds(delayInMilliseconds));
+
+ object actual;
+ if (pollingInterval > 0)
+ {
+ long nextPoll = TimestampOffset(now, TimeSpan.FromMilliseconds(pollingInterval));
+ while ((now = Stopwatch.GetTimestamp()) < delayEnd)
+ {
+ if (nextPoll > now)
+ Thread.Sleep((int)TimestampDiff(delayEnd < nextPoll ? delayEnd : nextPoll, now).TotalMilliseconds);
+ nextPoll = TimestampOffset(now, TimeSpan.FromMilliseconds(pollingInterval));
+
+ actual = InvokeDelegate(del);
+
+ try
+ {
+ ConstraintResult result = BaseConstraint.ApplyTo(actual);
+ if (result.IsSuccess)
+ return new ConstraintResult(this, actual, true);
+ }
+ catch(Exception)
+ {
+ // Ignore any exceptions when polling
+ }
+ }
+ }
+ if ((now = Stopwatch.GetTimestamp()) < delayEnd)
+ Thread.Sleep((int)TimestampDiff(delayEnd, now).TotalMilliseconds);
+
+ actual = InvokeDelegate(del);
+ return new ConstraintResult(this, actual, BaseConstraint.ApplyTo(actual).IsSuccess);
+ }
+
+ private static object InvokeDelegate<T>(ActualValueDelegate<T> del)
+ {
+#if NET_4_0 || NET_4_5
+ if (AsyncInvocationRegion.IsAsyncOperation(del))
+ using (AsyncInvocationRegion region = AsyncInvocationRegion.Create(del))
+ return region.WaitForPendingOperationsToComplete(del());
+#endif
+
+ return del();
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given reference.
+ /// Overridden to wait for the specified delay period before
+ /// calling the base constraint with the dereferenced value.
+ /// </summary>
+ /// <param name="actual">A reference to the value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(ref TActual actual)
+ {
+ long now = Stopwatch.GetTimestamp();
+ long delayEnd = TimestampOffset(now, TimeSpan.FromMilliseconds(delayInMilliseconds));
+
+ if (pollingInterval > 0)
+ {
+ long nextPoll = TimestampOffset(now, TimeSpan.FromMilliseconds(pollingInterval));
+ while ((now = Stopwatch.GetTimestamp()) < delayEnd)
+ {
+ if (nextPoll > now)
+ Thread.Sleep((int)TimestampDiff(delayEnd < nextPoll ? delayEnd : nextPoll, now).TotalMilliseconds);
+ nextPoll = TimestampOffset(now, TimeSpan.FromMilliseconds(pollingInterval));
+
+ try
+ {
+ ConstraintResult result = BaseConstraint.ApplyTo(actual);
+ if (result.IsSuccess)
+ return new ConstraintResult(this, actual, true);
+ }
+ catch(Exception)
+ {
+ // Ignore any exceptions when polling
+ }
+ }
+ }
+ if ((now = Stopwatch.GetTimestamp()) < delayEnd)
+ Thread.Sleep((int)TimestampDiff(delayEnd, now).TotalMilliseconds);
+
+ return new ConstraintResult(this, actual, BaseConstraint.ApplyTo(actual).IsSuccess);
+ }
+
+ /// <summary>
+ /// Returns the string representation of the constraint.
+ /// </summary>
+ protected override string GetStringRepresentation()
+ {
+ return string.Format("<after {0} {1}>", delayInMilliseconds, BaseConstraint);
+ }
+
+ /// <summary>
+ /// Adjusts a Timestamp by a given TimeSpan
+ /// </summary>
+ /// <param name="timestamp"></param>
+ /// <param name="offset"></param>
+ /// <returns></returns>
+ private static long TimestampOffset(long timestamp, TimeSpan offset)
+ {
+ return timestamp + (long)(offset.TotalSeconds * Stopwatch.Frequency);
+ }
+
+ /// <summary>
+ /// Returns the difference between two Timestamps as a TimeSpan
+ /// </summary>
+ /// <param name="timestamp1"></param>
+ /// <param name="timestamp2"></param>
+ /// <returns></returns>
+ private static TimeSpan TimestampDiff(long timestamp1, long timestamp2)
+ {
+ return TimeSpan.FromSeconds((double)(timestamp1 - timestamp2) / Stopwatch.Frequency);
+ }
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// DictionaryContainsKeyConstraint is used to test whether a dictionary
+ /// contains an expected object as a key.
+ /// </summary>
+ public class DictionaryContainsKeyConstraint : CollectionContainsConstraint
+ {
+ /// <summary>
+ /// Construct a DictionaryContainsKeyConstraint
+ /// </summary>
+ /// <param name="expected"></param>
+ public DictionaryContainsKeyConstraint(object expected)
+ : base(expected)
+ {
+ }
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public override string DisplayName { get { return "ContainsKey"; } }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "dictionary containing key " + MsgUtils.FormatValue(Expected); }
+ }
+
+ /// <summary>
+ /// Test whether the expected key is contained in the dictionary
+ /// </summary>
+ protected override bool Matches(IEnumerable actual)
+ {
+ IDictionary dictionary = actual as IDictionary;
+
+ if (dictionary == null)
+ throw new ArgumentException("The actual value must be an IDictionary", "actual");
+
+ return base.Matches(dictionary.Keys);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// DictionaryContainsValueConstraint is used to test whether a dictionary
+ /// contains an expected object as a value.
+ /// </summary>
+ public class DictionaryContainsValueConstraint : CollectionContainsConstraint
+ {
+ /// <summary>
+ /// Construct a DictionaryContainsValueConstraint
+ /// </summary>
+ /// <param name="expected"></param>
+ public DictionaryContainsValueConstraint(object expected)
+ : base(expected)
+ {
+ }
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public override string DisplayName { get { return "ContainsValue"; } }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "dictionary containing value " + MsgUtils.FormatValue(Expected); }
+ }
+
+ /// <summary>
+ /// Test whether the expected value is contained in the dictionary
+ /// </summary>
+ protected override bool Matches(IEnumerable actual)
+ {
+ IDictionary dictionary = actual as IDictionary;
+
+ if (dictionary == null)
+ throw new ArgumentException("The actual value must be an IDictionary", "actual");
+
+ return base.Matches(dictionary.Values);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// EmptyCollectionConstraint tests whether a collection is empty.
+ /// </summary>
+ public class EmptyCollectionConstraint : CollectionConstraint
+ {
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "<empty>"; }
+ }
+
+ /// <summary>
+ /// Check that the collection is empty
+ /// </summary>
+ /// <param name="collection"></param>
+ /// <returns></returns>
+ protected override bool Matches(IEnumerable collection)
+ {
+ return IsEmpty(collection);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// EmptyConstraint tests a whether a string or collection is empty,
+ /// postponing the decision about which test is applied until the
+ /// type of the actual argument is known.
+ /// </summary>
+ public class EmptyConstraint : Constraint
+ {
+ private Constraint realConstraint;
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return realConstraint == null ? "<empty>" : realConstraint.Description; }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ // NOTE: actual is string will fail for a null typed as string
+ if (typeof(TActual) == typeof(string))
+ realConstraint = new EmptyStringConstraint();
+ else if (actual == null)
+ throw new System.ArgumentException("The actual value must be a string or a non-null IEnumerable or DirectoryInfo", "actual");
+#if !SILVERLIGHT && !PORTABLE
+ else if (actual is System.IO.DirectoryInfo)
+ realConstraint = new EmptyDirectoryConstraint();
+#endif
+ else
+ realConstraint = new EmptyCollectionConstraint();
+
+ return realConstraint.ApplyTo(actual);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !SILVERLIGHT && !PORTABLE
+using System;
+using System.IO;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// EmptyDirectoryConstraint is used to test that a directory is empty
+ /// </summary>
+ public class EmptyDirectoryConstraint : Constraint
+ {
+ private int files = 0;
+ private int subdirs = 0;
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "an empty directory"; }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ DirectoryInfo dirInfo = actual as DirectoryInfo;
+ if (dirInfo == null)
+ throw new ArgumentException("The actual value must be a DirectoryInfo", "actual");
+ files = dirInfo.GetFiles().Length;
+ subdirs = dirInfo.GetDirectories().Length;
+ bool hasSucceeded = files == 0 && subdirs == 0;
+
+ return new ConstraintResult(this, actual, hasSucceeded);
+ }
+
+ // TODO: Decide if we need a special result for this
+ ///// <summary>
+ ///// Write the actual value for a failing constraint test to a
+ ///// MessageWriter. The default implementation simply writes
+ ///// the raw value of actual, leaving it to the writer to
+ ///// perform any formatting.
+ ///// </summary>
+ ///// <param name="writer">The writer on which the actual value is displayed</param>
+ //public override void WriteActualValueTo(MessageWriter writer)
+ //{
+ // DirectoryInfo dir = actual as DirectoryInfo;
+ // if (dir == null)
+ // base.WriteActualValueTo(writer);
+ // else
+ // {
+ // writer.WriteActualValue(dir);
+ // writer.Write(" with {0} files and {1} directories", files, subdirs);
+ // }
+ //}
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// EmptyStringConstraint tests whether a string is empty.
+ /// </summary>
+ public class EmptyStringConstraint : StringConstraint
+ {
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "<empty>"; }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ protected override bool Matches(string actual)
+ {
+ return actual == string.Empty;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// EndsWithConstraint can test whether a string ends
+ /// with an expected substring.
+ /// </summary>
+ public class EndsWithConstraint : StringConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndsWithConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The expected string</param>
+ public EndsWithConstraint(string expected) : base(expected)
+ {
+ this.descriptionText = "String ending with";
+ }
+
+ /// <summary>
+ /// Test whether the constraint is matched by the actual value.
+ /// This is a template method, which calls the IsMatch method
+ /// of the derived class.
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ protected override bool Matches(string actual)
+ {
+ if (this.caseInsensitive)
+ return actual != null && actual.ToLower().EndsWith(expected.ToLower());
+ else
+ return actual != null && actual.EndsWith(expected);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// EqualConstraint is able to compare an actual value with the
+ /// expected value provided in its constructor. Two objects are
+ /// considered equal if both are null, or if both have the same
+ /// value. NUnit has special semantics for some object types.
+ /// </summary>
+ public class EqualConstraint : Constraint
+ {
+ #region Static and Instance Fields
+
+ private readonly object _expected;
+
+ private Tolerance _tolerance = Tolerance.Default;
+
+ /// <summary>
+ /// NUnitEqualityComparer used to test equality.
+ /// </summary>
+ private NUnitEqualityComparer _comparer = new NUnitEqualityComparer();
+
+ #endregion
+
+ #region Constructor
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EqualConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The expected value.</param>
+ public EqualConstraint(object expected)
+ : base(expected)
+ {
+ AdjustArgumentIfNeeded(ref expected);
+
+ _expected = expected;
+ ClipStrings = true;
+ }
+ #endregion
+
+ #region Properties
+
+ // TODO: Remove public properties
+ // They are only used by EqualConstraintResult
+ // EqualConstraint should inject them into the constructor.
+
+ /// <summary>
+ /// Gets the tolerance for this comparison.
+ /// </summary>
+ /// <value>
+ /// The tolerance.
+ /// </value>
+ public Tolerance Tolerance
+ {
+ get { return _tolerance; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether to compare case insensitive.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if comparing case insensitive; otherwise, <c>false</c>.
+ /// </value>
+ public bool CaseInsensitive
+ {
+ get { return _comparer.IgnoreCase; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether or not to clip strings.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if set to clip strings otherwise, <c>false</c>.
+ /// </value>
+ public bool ClipStrings { get; private set; }
+
+ /// <summary>
+ /// Gets the failure points.
+ /// </summary>
+ /// <value>
+ /// The failure points.
+ /// </value>
+ public IList<NUnitEqualityComparer.FailurePoint> FailurePoints
+ {
+ get { return _comparer.FailurePoints; }
+ }
+
+ #endregion
+
+ #region Constraint Modifiers
+ /// <summary>
+ /// Flag the constraint to ignore case and return self.
+ /// </summary>
+ public EqualConstraint IgnoreCase
+ {
+ get
+ {
+ _comparer.IgnoreCase = true;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Flag the constraint to suppress string clipping
+ /// and return self.
+ /// </summary>
+ public EqualConstraint NoClip
+ {
+ get
+ {
+ ClipStrings = false;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Flag the constraint to compare arrays as collections
+ /// and return self.
+ /// </summary>
+ public EqualConstraint AsCollection
+ {
+ get
+ {
+ _comparer.CompareAsCollection = true;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Flag the constraint to use a tolerance when determining equality.
+ /// </summary>
+ /// <param name="amount">Tolerance value to be used</param>
+ /// <returns>Self.</returns>
+ public EqualConstraint Within(object amount)
+ {
+ if (!_tolerance.IsUnsetOrDefault)
+ throw new InvalidOperationException("Within modifier may appear only once in a constraint expression");
+
+ _tolerance = new Tolerance(amount);
+ return this;
+ }
+
+#if !NETCF
+ /// <summary>
+ /// Flags the constraint to include <see cref="DateTimeOffset.Offset"/>
+ /// property in comparison of two <see cref="DateTimeOffset"/> values.
+ /// </summary>
+ /// <remarks>
+ /// Using this modifier does not allow to use the <see cref="Within"/>
+ /// constraint modifier.
+ /// </remarks>
+ public EqualConstraint WithSameOffset
+ {
+ get
+ {
+ _comparer.WithSameOffset = true;
+ return this;
+ }
+ }
+#endif
+
+ /// <summary>
+ /// Switches the .Within() modifier to interpret its tolerance as
+ /// a distance in representable _values (see remarks).
+ /// </summary>
+ /// <returns>Self.</returns>
+ /// <remarks>
+ /// Ulp stands for "unit in the last place" and describes the minimum
+ /// amount a given value can change. For any integers, an ulp is 1 whole
+ /// digit. For floating point _values, the accuracy of which is better
+ /// for smaller numbers and worse for larger numbers, an ulp depends
+ /// on the size of the number. Using ulps for comparison of floating
+ /// point results instead of fixed tolerances is safer because it will
+ /// automatically compensate for the added inaccuracy of larger numbers.
+ /// </remarks>
+ public EqualConstraint Ulps
+ {
+ get
+ {
+ _tolerance = _tolerance.Ulps;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Switches the .Within() modifier to interpret its tolerance as
+ /// a percentage that the actual _values is allowed to deviate from
+ /// the expected value.
+ /// </summary>
+ /// <returns>Self</returns>
+ public EqualConstraint Percent
+ {
+ get
+ {
+ _tolerance = _tolerance.Percent;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Causes the tolerance to be interpreted as a TimeSpan in days.
+ /// </summary>
+ /// <returns>Self</returns>
+ public EqualConstraint Days
+ {
+ get
+ {
+ _tolerance = _tolerance.Days;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Causes the tolerance to be interpreted as a TimeSpan in hours.
+ /// </summary>
+ /// <returns>Self</returns>
+ public EqualConstraint Hours
+ {
+ get
+ {
+ _tolerance = _tolerance.Hours;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Causes the tolerance to be interpreted as a TimeSpan in minutes.
+ /// </summary>
+ /// <returns>Self</returns>
+ public EqualConstraint Minutes
+ {
+ get
+ {
+ _tolerance = _tolerance.Minutes;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Causes the tolerance to be interpreted as a TimeSpan in seconds.
+ /// </summary>
+ /// <returns>Self</returns>
+ public EqualConstraint Seconds
+ {
+ get
+ {
+ _tolerance = _tolerance.Seconds;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Causes the tolerance to be interpreted as a TimeSpan in milliseconds.
+ /// </summary>
+ /// <returns>Self</returns>
+ public EqualConstraint Milliseconds
+ {
+ get
+ {
+ _tolerance = _tolerance.Milliseconds;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Causes the tolerance to be interpreted as a TimeSpan in clock ticks.
+ /// </summary>
+ /// <returns>Self</returns>
+ public EqualConstraint Ticks
+ {
+ get
+ {
+ _tolerance = _tolerance.Ticks;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Flag the constraint to use the supplied IComparer object.
+ /// </summary>
+ /// <param name="comparer">The IComparer object to use.</param>
+ /// <returns>Self.</returns>
+ public EqualConstraint Using(IComparer comparer)
+ {
+ _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
+ return this;
+ }
+
+ /// <summary>
+ /// Flag the constraint to use the supplied IComparer object.
+ /// </summary>
+ /// <param name="comparer">The IComparer object to use.</param>
+ /// <returns>Self.</returns>
+ public EqualConstraint Using<T>(IComparer<T> comparer)
+ {
+ _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
+ return this;
+ }
+
+ /// <summary>
+ /// Flag the constraint to use the supplied Comparison object.
+ /// </summary>
+ /// <param name="comparer">The IComparer object to use.</param>
+ /// <returns>Self.</returns>
+ public EqualConstraint Using<T>(Comparison<T> comparer)
+ {
+ _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
+ return this;
+ }
+
+ /// <summary>
+ /// Flag the constraint to use the supplied IEqualityComparer object.
+ /// </summary>
+ /// <param name="comparer">The IComparer object to use.</param>
+ /// <returns>Self.</returns>
+ public EqualConstraint Using(IEqualityComparer comparer)
+ {
+ _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
+ return this;
+ }
+
+ /// <summary>
+ /// Flag the constraint to use the supplied IEqualityComparer object.
+ /// </summary>
+ /// <param name="comparer">The IComparer object to use.</param>
+ /// <returns>Self.</returns>
+ public EqualConstraint Using<T>(IEqualityComparer<T> comparer)
+ {
+ _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
+ return this;
+ }
+
+ #endregion
+
+ #region Public Methods
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ AdjustArgumentIfNeeded(ref actual);
+ return new EqualConstraintResult(this, actual, _comparer.AreEqual(_expected, actual, ref _tolerance));
+ }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get
+ {
+ System.Text.StringBuilder sb = new System.Text.StringBuilder(MsgUtils.FormatValue(_expected));
+
+ if (_tolerance != null && !_tolerance.IsUnsetOrDefault)
+ {
+ sb.Append(" +/- ");
+ sb.Append(MsgUtils.FormatValue(_tolerance.Value));
+ if (_tolerance.Mode != ToleranceMode.Linear)
+ {
+ sb.Append(" ");
+ sb.Append(_tolerance.Mode.ToString());
+ }
+ }
+
+ if (_comparer.IgnoreCase)
+ sb.Append(", ignoring case");
+
+ return sb.ToString();
+ }
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ // Currently, we only adjust for ArraySegments that have a
+ // null array reference. Others could be added in the future.
+ private void AdjustArgumentIfNeeded<T>(ref T arg)
+ {
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ if (arg != null)
+ {
+ Type argType = arg.GetType();
+ Type genericTypeDefinition = argType.GetTypeInfo().IsGenericType ? argType.GetGenericTypeDefinition() : null;
+
+ if (genericTypeDefinition == typeof(ArraySegment<>) && argType.GetProperty("Array").GetValue(arg, null) == null)
+ {
+ var elementType = argType.GetGenericArguments()[0];
+ var array = Array.CreateInstance(elementType, 0);
+ var ctor = argType.GetConstructor(new Type[] { array.GetType() });
+ arg = (T)ctor.Invoke(new object[] { array });
+ }
+ }
+#endif
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// The EqualConstraintResult class is tailored for formatting
+ /// and displaying the result of an EqualConstraint.
+ /// </summary>
+ public class EqualConstraintResult : ConstraintResult
+ {
+ private object expectedValue;
+ private Tolerance tolerance;
+ private bool caseInsensitive;
+ private bool clipStrings;
+ private IList<NUnitEqualityComparer.FailurePoint> failurePoints;
+
+ #region Message Strings
+ private static readonly string StringsDiffer_1 =
+ "String lengths are both {0}. Strings differ at index {1}.";
+ private static readonly string StringsDiffer_2 =
+ "Expected string length {0} but was {1}. Strings differ at index {2}.";
+ private static readonly string StreamsDiffer_1 =
+ "Stream lengths are both {0}. Streams differ at offset {1}.";
+ private static readonly string StreamsDiffer_2 =
+ "Expected Stream length {0} but was {1}.";// Streams differ at offset {2}.";
+ private static readonly string CollectionType_1 =
+ "Expected and actual are both {0}";
+ private static readonly string CollectionType_2 =
+ "Expected is {0}, actual is {1}";
+ private static readonly string ValuesDiffer_1 =
+ "Values differ at index {0}";
+ private static readonly string ValuesDiffer_2 =
+ "Values differ at expected index {0}, actual index {1}";
+ #endregion
+
+ /// <summary>
+ /// Construct an EqualConstraintResult
+ /// </summary>
+ public EqualConstraintResult(EqualConstraint constraint, object actual, bool hasSucceeded)
+ : base(constraint, actual, hasSucceeded)
+ {
+ this.expectedValue = constraint.Arguments[0];
+ this.tolerance = constraint.Tolerance;
+ this.caseInsensitive = constraint.CaseInsensitive;
+ this.clipStrings = constraint.ClipStrings;
+ this.failurePoints = constraint.FailurePoints;
+ }
+
+ /// <summary>
+ /// Write a failure message. Overridden to provide custom
+ /// failure messages for EqualConstraint.
+ /// </summary>
+ /// <param name="writer">The MessageWriter to write to</param>
+ public override void WriteMessageTo(MessageWriter writer)
+ {
+ DisplayDifferences(writer, expectedValue, ActualValue, 0);
+ }
+
+ private void DisplayDifferences(MessageWriter writer, object expected, object actual, int depth)
+ {
+ if (expected is string && actual is string)
+ DisplayStringDifferences(writer, (string)expected, (string)actual);
+ else if (expected is ICollection && actual is ICollection)
+ DisplayCollectionDifferences(writer, (ICollection)expected, (ICollection)actual, depth);
+ else if (expected is IEnumerable && actual is IEnumerable)
+ DisplayEnumerableDifferences(writer, (IEnumerable)expected, (IEnumerable)actual, depth);
+ else if (expected is Stream && actual is Stream)
+ DisplayStreamDifferences(writer, (Stream)expected, (Stream)actual, depth);
+ else if (tolerance != null)
+ writer.DisplayDifferences(expected, actual, tolerance);
+ else
+ writer.DisplayDifferences(expected, actual);
+ }
+
+ #region DisplayStringDifferences
+ private void DisplayStringDifferences(MessageWriter writer, string expected, string actual)
+ {
+ int mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, caseInsensitive);
+
+ if (expected.Length == actual.Length)
+ writer.WriteMessageLine(StringsDiffer_1, expected.Length, mismatch);
+ else
+ writer.WriteMessageLine(StringsDiffer_2, expected.Length, actual.Length, mismatch);
+
+ writer.DisplayStringDifferences(expected, actual, mismatch, caseInsensitive, clipStrings);
+ }
+ #endregion
+
+ #region DisplayStreamDifferences
+ private void DisplayStreamDifferences(MessageWriter writer, Stream expected, Stream actual, int depth)
+ {
+ if (expected.Length == actual.Length)
+ {
+ long offset = failurePoints[depth].Position;
+ writer.WriteMessageLine(StreamsDiffer_1, expected.Length, offset);
+ }
+ else
+ writer.WriteMessageLine(StreamsDiffer_2, expected.Length, actual.Length);
+ }
+ #endregion
+
+ #region DisplayCollectionDifferences
+ /// <summary>
+ /// Display the failure information for two collections that did not match.
+ /// </summary>
+ /// <param name="writer">The MessageWriter on which to display</param>
+ /// <param name="expected">The expected collection.</param>
+ /// <param name="actual">The actual collection</param>
+ /// <param name="depth">The depth of this failure in a set of nested collections</param>
+ private void DisplayCollectionDifferences(MessageWriter writer, ICollection expected, ICollection actual, int depth)
+ {
+ DisplayTypesAndSizes(writer, expected, actual, depth);
+
+ if (failurePoints.Count > depth)
+ {
+ NUnitEqualityComparer.FailurePoint failurePoint = failurePoints[depth];
+
+ DisplayFailurePoint(writer, expected, actual, failurePoint, depth);
+
+ if (failurePoint.ExpectedHasData && failurePoint.ActualHasData)
+ DisplayDifferences(
+ writer,
+ failurePoint.ExpectedValue,
+ failurePoint.ActualValue,
+ ++depth);
+ else if (failurePoint.ActualHasData)
+ {
+ writer.Write(" Extra: ");
+ writer.WriteCollectionElements(actual, failurePoint.Position, 3);
+ }
+ else
+ {
+ writer.Write(" Missing: ");
+ writer.WriteCollectionElements(expected, failurePoint.Position, 3);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Displays a single line showing the types and sizes of the expected
+ /// and actual collections or arrays. If both are identical, the value is
+ /// only shown once.
+ /// </summary>
+ /// <param name="writer">The MessageWriter on which to display</param>
+ /// <param name="expected">The expected collection or array</param>
+ /// <param name="actual">The actual collection or array</param>
+ /// <param name="indent">The indentation level for the message line</param>
+ private void DisplayTypesAndSizes(MessageWriter writer, IEnumerable expected, IEnumerable actual, int indent)
+ {
+ string sExpected = MsgUtils.GetTypeRepresentation(expected);
+ if (expected is ICollection && !(expected is Array))
+ sExpected += string.Format(" with {0} elements", ((ICollection)expected).Count);
+
+ string sActual = MsgUtils.GetTypeRepresentation(actual);
+ if (actual is ICollection && !(actual is Array))
+ sActual += string.Format(" with {0} elements", ((ICollection)actual).Count);
+
+ if (sExpected == sActual)
+ writer.WriteMessageLine(indent, CollectionType_1, sExpected);
+ else
+ writer.WriteMessageLine(indent, CollectionType_2, sExpected, sActual);
+ }
+
+ /// <summary>
+ /// Displays a single line showing the point in the expected and actual
+ /// arrays at which the comparison failed. If the arrays have different
+ /// structures or dimensions, both _values are shown.
+ /// </summary>
+ /// <param name="writer">The MessageWriter on which to display</param>
+ /// <param name="expected">The expected array</param>
+ /// <param name="actual">The actual array</param>
+ /// <param name="failurePoint">Index of the failure point in the underlying collections</param>
+ /// <param name="indent">The indentation level for the message line</param>
+ private void DisplayFailurePoint(MessageWriter writer, IEnumerable expected, IEnumerable actual, NUnitEqualityComparer.FailurePoint failurePoint, int indent)
+ {
+ Array expectedArray = expected as Array;
+ Array actualArray = actual as Array;
+
+ int expectedRank = expectedArray != null ? expectedArray.Rank : 1;
+ int actualRank = actualArray != null ? actualArray.Rank : 1;
+
+ bool useOneIndex = expectedRank == actualRank;
+
+ if (expectedArray != null && actualArray != null)
+ for (int r = 1; r < expectedRank && useOneIndex; r++)
+ if (expectedArray.GetLength(r) != actualArray.GetLength(r))
+ useOneIndex = false;
+
+ int[] expectedIndices = MsgUtils.GetArrayIndicesFromCollectionIndex(expected, failurePoint.Position);
+ if (useOneIndex)
+ {
+ writer.WriteMessageLine(indent, ValuesDiffer_1, MsgUtils.GetArrayIndicesAsString(expectedIndices));
+ }
+ else
+ {
+ int[] actualIndices = MsgUtils.GetArrayIndicesFromCollectionIndex(actual, failurePoint.Position);
+ writer.WriteMessageLine(indent, ValuesDiffer_2,
+ MsgUtils.GetArrayIndicesAsString(expectedIndices), MsgUtils.GetArrayIndicesAsString(actualIndices));
+ }
+ }
+
+ private static object GetValueFromCollection(ICollection collection, int index)
+ {
+ Array array = collection as Array;
+
+ if (array != null && array.Rank > 1)
+ return array.GetValue(MsgUtils.GetArrayIndicesFromCollectionIndex(array, index));
+
+ if (collection is IList)
+ return ((IList)collection)[index];
+
+ foreach (object obj in collection)
+ if (--index < 0)
+ return obj;
+
+ return null;
+ }
+ #endregion
+
+ #region DisplayEnumerableDifferences
+
+ /// <summary>
+ /// Display the failure information for two IEnumerables that did not match.
+ /// </summary>
+ /// <param name="writer">The MessageWriter on which to display</param>
+ /// <param name="expected">The expected enumeration.</param>
+ /// <param name="actual">The actual enumeration</param>
+ /// <param name="depth">The depth of this failure in a set of nested collections</param>
+ private void DisplayEnumerableDifferences(MessageWriter writer, IEnumerable expected, IEnumerable actual, int depth)
+ {
+ DisplayTypesAndSizes(writer, expected, actual, depth);
+
+ if (failurePoints.Count > depth)
+ {
+ NUnitEqualityComparer.FailurePoint failurePoint = failurePoints[depth];
+
+ DisplayFailurePoint(writer, expected, actual, failurePoint, depth);
+
+ if (failurePoint.ExpectedHasData && failurePoint.ActualHasData)
+ DisplayDifferences(
+ writer,
+ failurePoint.ExpectedValue,
+ failurePoint.ActualValue,
+ ++depth);
+ //else if (failurePoint.ActualHasData)
+ //{
+ // writer.Write(" Extra: ");
+ // writer.WriteCollectionElements(actual, failurePoint.Position, 3);
+ //}
+ //else
+ //{
+ // writer.Write(" Missing: ");
+ // writer.WriteCollectionElements(expected, failurePoint.Position, 3);
+ //}
+ }
+ }
+
+ #endregion
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using NUnit.Compatibility;
+using System.Reflection;
+
+namespace NUnit.Framework.Constraints
+{
+
+ /// <summary>
+ /// EqualityAdapter class handles all equality comparisons
+ /// that use an <see cref="IEqualityComparer"/>, <see cref="IEqualityComparer{T}"/>
+ /// or a <see cref="ComparisonAdapter"/>.
+ /// </summary>
+ public abstract class EqualityAdapter
+ {
+ /// <summary>
+ /// Compares two objects, returning true if they are equal
+ /// </summary>
+ public abstract bool AreEqual(object x, object y);
+
+ /// <summary>
+ /// Returns true if the two objects can be compared by this adapter.
+ /// The base adapter cannot handle IEnumerables except for strings.
+ /// </summary>
+ public virtual bool CanCompare(object x, object y)
+ {
+ if (x is string && y is string)
+ return true;
+
+ if (x is IEnumerable || y is IEnumerable)
+ return false;
+
+ return true;
+ }
+
+ #region Nested IComparer Adapter
+
+ /// <summary>
+ /// Returns an <see cref="EqualityAdapter"/> that wraps an <see cref="IComparer"/>.
+ /// </summary>
+ public static EqualityAdapter For(IComparer comparer)
+ {
+ return new ComparerAdapter(comparer);
+ }
+
+ /// <summary>
+ /// <see cref="EqualityAdapter"/> that wraps an <see cref="IComparer"/>.
+ /// </summary>
+ class ComparerAdapter : EqualityAdapter
+ {
+ private IComparer comparer;
+
+ public ComparerAdapter(IComparer comparer)
+ {
+ this.comparer = comparer;
+ }
+
+ public override bool AreEqual(object x, object y)
+ {
+ return comparer.Compare(x, y) == 0;
+ }
+ }
+
+ #endregion
+
+ #region Nested IEqualityComparer Adapter
+
+ /// <summary>
+ /// Returns an <see cref="EqualityAdapter"/> that wraps an <see cref="IEqualityComparer"/>.
+ /// </summary>
+ public static EqualityAdapter For(IEqualityComparer comparer)
+ {
+ return new EqualityComparerAdapter(comparer);
+ }
+
+ class EqualityComparerAdapter : EqualityAdapter
+ {
+ private IEqualityComparer comparer;
+
+ public EqualityComparerAdapter(IEqualityComparer comparer)
+ {
+ this.comparer = comparer;
+ }
+
+ public override bool AreEqual(object x, object y)
+ {
+ return comparer.Equals(x, y);
+ }
+ }
+
+ /// <summary>
+ /// Returns an EqualityAdapter that uses a predicate function for items comparison.
+ /// </summary>
+ /// <typeparam name="TExpected"></typeparam>
+ /// <typeparam name="TActual"></typeparam>
+ /// <param name="comparison"></param>
+ /// <returns></returns>
+ public static EqualityAdapter For<TExpected, TActual>(Func<TExpected, TActual, bool> comparison)
+ {
+ return new PredicateEqualityAdapter<TExpected, TActual>(comparison);
+ }
+
+ internal class PredicateEqualityAdapter<TActual, TExpected> : EqualityAdapter
+ {
+ private readonly Func<TActual, TExpected, bool> _comparison;
+
+ /// <summary>
+ /// Returns true if the two objects can be compared by this adapter.
+ /// The base adapter cannot handle IEnumerables except for strings.
+ /// </summary>
+ public override bool CanCompare(object x, object y)
+ {
+ return true;
+ }
+
+ /// <summary>
+ /// Compares two objects, returning true if they are equal
+ /// </summary>
+ public override bool AreEqual(object x, object y)
+ {
+ return _comparison.Invoke((TActual)y, (TExpected)x);
+ }
+
+ public PredicateEqualityAdapter(Func<TActual, TExpected, bool> comparison)
+ {
+ _comparison = comparison;
+ }
+ }
+
+ #endregion
+
+ #region Nested GenericEqualityAdapter<T>
+
+ abstract class GenericEqualityAdapter<T> : EqualityAdapter
+ {
+ /// <summary>
+ /// Returns true if the two objects can be compared by this adapter.
+ /// Generic adapter requires objects of the specified type.
+ /// </summary>
+ public override bool CanCompare(object x, object y)
+ {
+ return typeof(T).GetTypeInfo().IsAssignableFrom(x.GetType().GetTypeInfo())
+ && typeof(T).GetTypeInfo().IsAssignableFrom(y.GetType().GetTypeInfo());
+ }
+
+ protected void ThrowIfNotCompatible(object x, object y)
+ {
+ if (!typeof(T).GetTypeInfo().IsAssignableFrom(x.GetType().GetTypeInfo()))
+ throw new ArgumentException("Cannot compare " + x.ToString());
+
+ if (!typeof(T).GetTypeInfo().IsAssignableFrom(y.GetType().GetTypeInfo()))
+ throw new ArgumentException("Cannot compare " + y.ToString());
+ }
+ }
+
+ #endregion
+
+ #region Nested IEqualityComparer<T> Adapter
+
+ /// <summary>
+ /// Returns an <see cref="EqualityAdapter"/> that wraps an <see cref="IEqualityComparer{T}"/>.
+ /// </summary>
+ public static EqualityAdapter For<T>(IEqualityComparer<T> comparer)
+ {
+ return new EqualityComparerAdapter<T>(comparer);
+ }
+
+ class EqualityComparerAdapter<T> : GenericEqualityAdapter<T>
+ {
+ private IEqualityComparer<T> comparer;
+
+ public EqualityComparerAdapter(IEqualityComparer<T> comparer)
+ {
+ this.comparer = comparer;
+ }
+
+ public override bool AreEqual(object x, object y)
+ {
+ ThrowIfNotCompatible(x, y);
+ return comparer.Equals((T)x, (T)y);
+ }
+ }
+
+ #endregion
+
+ #region Nested IComparer<T> Adapter
+
+ /// <summary>
+ /// Returns an <see cref="EqualityAdapter"/> that wraps an <see cref="IComparer{T}"/>.
+ /// </summary>
+ public static EqualityAdapter For<T>(IComparer<T> comparer)
+ {
+ return new ComparerAdapter<T>(comparer);
+ }
+
+ /// <summary>
+ /// <see cref="EqualityAdapter"/> that wraps an <see cref="IComparer"/>.
+ /// </summary>
+ class ComparerAdapter<T> : GenericEqualityAdapter<T>
+ {
+ private IComparer<T> comparer;
+
+ public ComparerAdapter(IComparer<T> comparer)
+ {
+ this.comparer = comparer;
+ }
+
+ public override bool AreEqual(object x, object y)
+ {
+ ThrowIfNotCompatible(x, y);
+ return comparer.Compare((T)x, (T)y) == 0;
+ }
+ }
+
+ #endregion
+
+ #region Nested Comparison<T> Adapter
+
+ /// <summary>
+ /// Returns an <see cref="EqualityAdapter"/> that wraps a <see cref="Comparison{T}"/>.
+ /// </summary>
+ public static EqualityAdapter For<T>(Comparison<T> comparer)
+ {
+ return new ComparisonAdapter<T>(comparer);
+ }
+
+ class ComparisonAdapter<T> : GenericEqualityAdapter<T>
+ {
+ private Comparison<T> comparer;
+
+ public ComparisonAdapter(Comparison<T> comparer)
+ {
+ this.comparer = comparer;
+ }
+
+ public override bool AreEqual(object x, object y)
+ {
+ ThrowIfNotCompatible(x, y);
+ return comparer.Invoke((T)x, (T)y) == 0;
+ }
+ }
+
+#endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// ExactCountConstraint applies another constraint to each
+ /// item in a collection, succeeding only if a specified
+ /// number of items succeed.
+ /// </summary>
+ public class ExactCountConstraint : PrefixConstraint
+ {
+ private int expectedCount;
+
+ /// <summary>
+ /// Construct an ExactCountConstraint on top of an existing constraint
+ /// </summary>
+ /// <param name="expectedCount"></param>
+ /// <param name="itemConstraint"></param>
+ public ExactCountConstraint(int expectedCount, IConstraint itemConstraint)
+ : base(itemConstraint)
+ {
+ this.expectedCount = expectedCount;
+ this.DescriptionPrefix = expectedCount == 0
+ ? "no item"
+ : expectedCount == 1
+ ? "exactly one item"
+ : string.Format("exactly {0} items", expectedCount);
+ }
+
+ /// <summary>
+ /// Apply the item constraint to each item in the collection,
+ /// succeeding only if the expected number of items pass.
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ if (!(actual is IEnumerable))
+ throw new ArgumentException("The actual value must be an IEnumerable", "actual");
+
+ int count = 0;
+ foreach (object item in (IEnumerable)actual)
+ if (BaseConstraint.ApplyTo(item).IsSuccess)
+ count++;
+
+ return new ConstraintResult(this, actual, count == expectedCount);
+ }
+ }
+}
+
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// ExactTypeConstraint is used to test that an object
+ /// is of the exact type provided in the constructor
+ /// </summary>
+ public class ExactTypeConstraint : TypeConstraint
+ {
+ /// <summary>
+ /// Construct an ExactTypeConstraint for a given Type
+ /// </summary>
+ /// <param name="type">The expected Type.</param>
+ public ExactTypeConstraint(Type type)
+ : base(type, string.Empty)
+ {
+ }
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public override string DisplayName { get { return "TypeOf"; } }
+
+ /// <summary>
+ /// Apply the constraint to an actual value, returning true if it succeeds
+ /// </summary>
+ /// <param name="actual">The actual argument</param>
+ /// <returns>True if the constraint succeeds, otherwise false.</returns>
+ protected override bool Matches(object actual)
+ {
+ return actual != null && actual.GetType() == expectedType;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Constraints
+{
+ internal class ExceptionNotThrownConstraint : Constraint
+ {
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "No Exception to be thrown"; }
+ }
+
+ /// <summary>
+ /// Applies the constraint to an actual value, returning a ConstraintResult.
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>A ConstraintResult</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ var exception = actual as Exception;
+ return new ConstraintResult(this, exception, exception == null);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// ExceptionTypeConstraint is a special version of ExactTypeConstraint
+ /// used to provided detailed info about the exception thrown in
+ /// an error message.
+ /// </summary>
+ public class ExceptionTypeConstraint : ExactTypeConstraint
+ {
+ /// <summary>
+ /// Constructs an ExceptionTypeConstraint
+ /// </summary>
+ public ExceptionTypeConstraint(Type type) : base(type) { }
+
+ /// <summary>
+ /// Applies the constraint to an actual value, returning a ConstraintResult.
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>A ConstraintResult</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ Exception castedToException = actual as Exception;
+
+ if (actual != null && castedToException == null)
+ throw new ArgumentException("Actual value must be an Exception", "actual");
+
+ actualType = actual == null ? null : actual.GetType();
+
+ return new ExceptionTypeConstraintResult(this, actual, actualType, this.Matches(actual));
+ }
+
+ #region Nested Result Class
+ class ExceptionTypeConstraintResult : ConstraintResult
+ {
+ private readonly object caughtException;
+
+ public ExceptionTypeConstraintResult(ExceptionTypeConstraint constraint, object caughtException, Type type, bool matches)
+ : base(constraint, type, matches)
+ {
+ this.caughtException = caughtException;
+ }
+
+ public override void WriteActualValueTo(MessageWriter writer)
+ {
+ if (this.Status == ConstraintStatus.Failure)
+ {
+ Exception ex = caughtException as Exception;
+
+ if (ex == null)
+ {
+ base.WriteActualValueTo(writer);
+ }
+ else
+ {
+ writer.WriteActualValue(ex);
+ }
+ }
+ }
+ }
+ #endregion
+ }
+}
+
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// FalseConstraint tests that the actual value is false
+ /// </summary>
+ public class FalseConstraint : Constraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FalseConstraint"/> class.
+ /// </summary>
+ public FalseConstraint()
+ {
+ this.Description = "False";
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ return new ConstraintResult(this, actual, false.Equals(actual));
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !SILVERLIGHT && !PORTABLE
+using System;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// FileExistsConstraint is used to determine if a file exists
+ /// </summary>
+ [Obsolete("FileExistsConstraint is deprecated, please use FileOrDirectoryExistsConstraint instead.")]
+ public class FileExistsConstraint : FileOrDirectoryExistsConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FileExistsConstraint"/> class.
+ /// </summary>
+ public FileExistsConstraint() : base(true)
+ {
+ }
+
+#region Overrides of Constraint
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "file exists"; }
+ }
+
+#endregion
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if (!SILVERLIGHT && !PORTABLE) || TIZEN
+using System;
+using System.IO;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// FileOrDirectoryExistsConstraint is used to determine if a file or directory exists
+ /// </summary>
+ public class FileOrDirectoryExistsConstraint : Constraint
+ {
+ private bool _ignoreDirectories;
+ private bool _ignoreFiles;
+
+ /// <summary>
+ /// If true, the constraint will only check if files exist, not directories
+ /// </summary>
+ public FileOrDirectoryExistsConstraint IgnoreDirectories
+ {
+ get
+ {
+ _ignoreDirectories = true;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// If true, the constraint will only check if directories exist, not files
+ /// </summary>
+ public FileOrDirectoryExistsConstraint IgnoreFiles
+ {
+ get
+ {
+ _ignoreFiles = true;
+ return this;
+ }
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FileOrDirectoryExistsConstraint"/> class that
+ /// will check files and directories.
+ /// </summary>
+ public FileOrDirectoryExistsConstraint(){}
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FileOrDirectoryExistsConstraint"/> class that
+ /// will only check files if ignoreDirectories is true.
+ /// </summary>
+ /// <param name="ignoreDirectories">if set to <c>true</c> [ignore directories].</param>
+ public FileOrDirectoryExistsConstraint(bool ignoreDirectories)
+ {
+ _ignoreDirectories = ignoreDirectories;
+ }
+
+#region Overrides of Constraint
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get
+ {
+ if (_ignoreDirectories)
+ {
+ return "file exists";
+ }
+ if (_ignoreFiles)
+ {
+ return "directory exists";
+ }
+ return "file or directory exists";
+ }
+ }
+
+ /// <summary>
+ /// Applies the constraint to an actual value, returning a ConstraintResult.
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>A ConstraintResult</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ if(actual == null)
+ throw new ArgumentNullException("actual", "The actual value must be a non-null string" + ErrorSubstring);
+
+ if(actual is string)
+ {
+ return CheckString(actual);
+ }
+
+ var fileInfo = actual as FileInfo;
+ if (!_ignoreFiles && fileInfo != null)
+ {
+ return new ConstraintResult(this, actual, fileInfo.Exists);
+ }
+
+ var directoryInfo = actual as DirectoryInfo;
+ if (!_ignoreDirectories && directoryInfo != null)
+ {
+ return new ConstraintResult(this, actual, directoryInfo.Exists);
+ }
+ throw new ArgumentException("The actual value must be a string" + ErrorSubstring, "actual");
+ }
+
+ private ConstraintResult CheckString<TActual>(TActual actual)
+ {
+ var str = actual as string;
+ if (String.IsNullOrEmpty(str))
+ throw new ArgumentException("The actual value cannot be an empty string", "actual");
+
+ var fileInfo = new FileInfo(str);
+ if (_ignoreDirectories && !_ignoreFiles)
+ {
+ return new ConstraintResult(this, actual, fileInfo.Exists);
+ }
+ var directoryInfo = new DirectoryInfo(str);
+ if (_ignoreFiles && !_ignoreDirectories)
+ {
+ return new ConstraintResult(this, actual, directoryInfo.Exists);
+ }
+ return new ConstraintResult(this, actual, fileInfo.Exists || directoryInfo.Exists);
+ }
+
+ private string ErrorSubstring
+ {
+ get
+ {
+ if (_ignoreDirectories)
+ {
+ return " or FileInfo";
+ }
+ if (_ignoreFiles)
+ {
+ return " or DirectoryInfo";
+ }
+ return ", FileInfo or DirectoryInfo";
+ }
+ }
+
+#endregion
+
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Runtime.InteropServices;
+
+namespace NUnit.Framework.Constraints
+{
+
+ /// <summary>Helper routines for working with floating point numbers</summary>
+ /// <remarks>
+ /// <para>
+ /// The floating point comparison code is based on this excellent article:
+ /// http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
+ /// </para>
+ /// <para>
+ /// "ULP" means Unit in the Last Place and in the context of this library refers to
+ /// the distance between two adjacent floating point numbers. IEEE floating point
+ /// numbers can only represent a finite subset of natural numbers, with greater
+ /// accuracy for smaller numbers and lower accuracy for very large numbers.
+ /// </para>
+ /// <para>
+ /// If a comparison is allowed "2 ulps" of deviation, that means the _values are
+ /// allowed to deviate by up to 2 adjacent floating point _values, which might be
+ /// as low as 0.0000001 for small numbers or as high as 10.0 for large numbers.
+ /// </para>
+ /// </remarks>
+ public class FloatingPointNumerics
+ {
+
+ #region struct FloatIntUnion
+
+ /// <summary>Union of a floating point variable and an integer</summary>
+ [StructLayout(LayoutKind.Explicit)]
+ private struct FloatIntUnion
+ {
+ /// <summary>The union's value as a floating point variable</summary>
+ [FieldOffset(0)]
+ public float Float;
+
+ /// <summary>The union's value as an integer</summary>
+ [FieldOffset(0)]
+ public int Int;
+
+ /// <summary>The union's value as an unsigned integer</summary>
+ [FieldOffset(0)]
+ public uint UInt;
+ }
+
+ #endregion // struct FloatIntUnion
+
+ #region struct DoubleLongUnion
+
+ /// <summary>Union of a double precision floating point variable and a long</summary>
+ [StructLayout(LayoutKind.Explicit)]
+ private struct DoubleLongUnion
+ {
+ /// <summary>The union's value as a double precision floating point variable</summary>
+ [FieldOffset(0)]
+ public double Double;
+
+ /// <summary>The union's value as a long</summary>
+ [FieldOffset(0)]
+ public long Long;
+
+ /// <summary>The union's value as an unsigned long</summary>
+ [FieldOffset(0)]
+ public ulong ULong;
+ }
+
+ #endregion // struct DoubleLongUnion
+
+ /// <summary>Compares two floating point _values for equality</summary>
+ /// <param name="left">First floating point value to be compared</param>
+ /// <param name="right">Second floating point value t be compared</param>
+ /// <param name="maxUlps">
+ /// Maximum number of representable floating point _values that are allowed to
+ /// be between the left and the right floating point _values
+ /// </param>
+ /// <returns>True if both numbers are equal or close to being equal</returns>
+ /// <remarks>
+ /// <para>
+ /// Floating point _values can only represent a finite subset of natural numbers.
+ /// For example, the _values 2.00000000 and 2.00000024 can be stored in a float,
+ /// but nothing inbetween them.
+ /// </para>
+ /// <para>
+ /// This comparison will count how many possible floating point _values are between
+ /// the left and the right number. If the number of possible _values between both
+ /// numbers is less than or equal to maxUlps, then the numbers are considered as
+ /// being equal.
+ /// </para>
+ /// <para>
+ /// Implementation partially follows the code outlined here:
+ /// http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/
+ /// </para>
+ /// </remarks>
+ public static bool AreAlmostEqualUlps(float left, float right, int maxUlps)
+ {
+ FloatIntUnion leftUnion = new FloatIntUnion();
+ FloatIntUnion rightUnion = new FloatIntUnion();
+
+ leftUnion.Float = left;
+ rightUnion.Float = right;
+
+ uint leftSignMask = (leftUnion.UInt >> 31);
+ uint rightSignMask = (rightUnion.UInt >> 31);
+
+ uint leftTemp = ((0x80000000 - leftUnion.UInt) & leftSignMask);
+ leftUnion.UInt = leftTemp | (leftUnion.UInt & ~leftSignMask);
+
+ uint rightTemp = ((0x80000000 - rightUnion.UInt) & rightSignMask);
+ rightUnion.UInt = rightTemp | (rightUnion.UInt & ~rightSignMask);
+
+ if (leftSignMask != rightSignMask) // Overflow possible, check each against zero
+ {
+ if (Math.Abs(leftUnion.Int) > maxUlps || Math.Abs(rightUnion.Int) > maxUlps)
+ return false;
+ }
+
+ // Either they have the same sign or both are very close to zero
+ return Math.Abs(leftUnion.Int - rightUnion.Int) <= maxUlps;
+ }
+
+ /// <summary>Compares two double precision floating point _values for equality</summary>
+ /// <param name="left">First double precision floating point value to be compared</param>
+ /// <param name="right">Second double precision floating point value t be compared</param>
+ /// <param name="maxUlps">
+ /// Maximum number of representable double precision floating point _values that are
+ /// allowed to be between the left and the right double precision floating point _values
+ /// </param>
+ /// <returns>True if both numbers are equal or close to being equal</returns>
+ /// <remarks>
+ /// <para>
+ /// Double precision floating point _values can only represent a limited series of
+ /// natural numbers. For example, the _values 2.0000000000000000 and 2.0000000000000004
+ /// can be stored in a double, but nothing inbetween them.
+ /// </para>
+ /// <para>
+ /// This comparison will count how many possible double precision floating point
+ /// _values are between the left and the right number. If the number of possible
+ /// _values between both numbers is less than or equal to maxUlps, then the numbers
+ /// are considered as being equal.
+ /// </para>
+ /// <para>
+ /// Implementation partially follows the code outlined here:
+ /// http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/
+ /// </para>
+ /// </remarks>
+ public static bool AreAlmostEqualUlps(double left, double right, long maxUlps)
+ {
+ DoubleLongUnion leftUnion = new DoubleLongUnion();
+ DoubleLongUnion rightUnion = new DoubleLongUnion();
+
+ leftUnion.Double = left;
+ rightUnion.Double = right;
+
+ ulong leftSignMask = (leftUnion.ULong >> 63);
+ ulong rightSignMask = (rightUnion.ULong >> 63);
+
+ ulong leftTemp = ((0x8000000000000000 - leftUnion.ULong) & leftSignMask);
+ leftUnion.ULong = leftTemp | (leftUnion.ULong & ~leftSignMask);
+
+ ulong rightTemp = ((0x8000000000000000 - rightUnion.ULong) & rightSignMask);
+ rightUnion.ULong = rightTemp | (rightUnion.ULong & ~rightSignMask);
+
+ if (leftSignMask != rightSignMask) // Overflow possible, check each against zero
+ {
+ if (Math.Abs(leftUnion.Long) > maxUlps || Math.Abs(rightUnion.Long) > maxUlps)
+ return false;
+ }
+
+ // Either they have the same sign or both are very close to zero
+ return Math.Abs(leftUnion.Long - rightUnion.Long) <= maxUlps;
+ }
+
+ /// <summary>
+ /// Reinterprets the memory contents of a floating point value as an integer value
+ /// </summary>
+ /// <param name="value">
+ /// Floating point value whose memory contents to reinterpret
+ /// </param>
+ /// <returns>
+ /// The memory contents of the floating point value interpreted as an integer
+ /// </returns>
+ public static int ReinterpretAsInt(float value)
+ {
+ FloatIntUnion union = new FloatIntUnion();
+ union.Float = value;
+ return union.Int;
+ }
+
+ /// <summary>
+ /// Reinterprets the memory contents of a double precision floating point
+ /// value as an integer value
+ /// </summary>
+ /// <param name="value">
+ /// Double precision floating point value whose memory contents to reinterpret
+ /// </param>
+ /// <returns>
+ /// The memory contents of the double precision floating point value
+ /// interpreted as an integer
+ /// </returns>
+ public static long ReinterpretAsLong(double value)
+ {
+ DoubleLongUnion union = new DoubleLongUnion();
+ union.Double = value;
+ return union.Long;
+ }
+
+ /// <summary>
+ /// Reinterprets the memory contents of an integer as a floating point value
+ /// </summary>
+ /// <param name="value">Integer value whose memory contents to reinterpret</param>
+ /// <returns>
+ /// The memory contents of the integer value interpreted as a floating point value
+ /// </returns>
+ public static float ReinterpretAsFloat(int value)
+ {
+ FloatIntUnion union = new FloatIntUnion();
+ union.Int = value;
+ return union.Float;
+ }
+
+ /// <summary>
+ /// Reinterprets the memory contents of an integer value as a double precision
+ /// floating point value
+ /// </summary>
+ /// <param name="value">Integer whose memory contents to reinterpret</param>
+ /// <returns>
+ /// The memory contents of the integer interpreted as a double precision
+ /// floating point value
+ /// </returns>
+ public static double ReinterpretAsDouble(long value)
+ {
+ DoubleLongUnion union = new DoubleLongUnion();
+ union.Long = value;
+ return union.Double;
+ }
+
+ private FloatingPointNumerics()
+ {
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Tests whether a value is greater than the value supplied to its constructor
+ /// </summary>
+ public class GreaterThanConstraint : ComparisonConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GreaterThanConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The expected value.</param>
+ public GreaterThanConstraint(object expected) : base(expected, false, false, true, "greater than") { }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Tests whether a value is greater than or equal to the value supplied to its constructor
+ /// </summary>
+ public class GreaterThanOrEqualConstraint : ComparisonConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GreaterThanOrEqualConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The expected value.</param>
+ public GreaterThanOrEqualConstraint(object expected) : base(expected, false, true, true, "greater than or equal to") { }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Interface for all constraints
+ /// </summary>
+ public interface IConstraint : IResolveConstraint
+ {
+ #region Properties
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// </summary>
+ string DisplayName { get; }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ string Description { get; }
+
+ /// <summary>
+ /// Arguments provided to this Constraint, for use in
+ /// formatting the description.
+ /// </summary>
+ object[] Arguments { get; }
+
+ /// <summary>
+ /// The ConstraintBuilder holding this constraint
+ /// </summary>
+ ConstraintBuilder Builder { get; set; }
+
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Applies the constraint to an actual value, returning a ConstraintResult.
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>A ConstraintResult</returns>
+ ConstraintResult ApplyTo<TActual>(TActual actual);
+
+ /// <summary>
+ /// Applies the constraint to an ActualValueDelegate that returns
+ /// the value to be tested. The default implementation simply evaluates
+ /// the delegate but derived classes may override it to provide for
+ /// delayed processing.
+ /// </summary>
+ /// <param name="del">An ActualValueDelegate</param>
+ /// <returns>A ConstraintResult</returns>
+ ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del);
+
+ #pragma warning disable 3006
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given reference.
+ /// The default implementation simply dereferences the value but
+ /// derived classes may override it to provide for delayed processing.
+ /// </summary>
+ /// <param name="actual">A reference to the value to be tested</param>
+ /// <returns>A ConstraintResult</returns>
+ ConstraintResult ApplyTo<TActual>(ref TActual actual);
+ #pragma warning restore 3006
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// The IResolveConstraint interface is implemented by all
+ /// complete and resolvable constraints and expressions.
+ /// </summary>
+ public interface IResolveConstraint
+ {
+ /// <summary>
+ /// Return the top-level constraint for this expression
+ /// </summary>
+ /// <returns></returns>
+ IConstraint Resolve();
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// InstanceOfTypeConstraint is used to test that an object
+ /// is of the same type provided or derived from it.
+ /// </summary>
+ public class InstanceOfTypeConstraint : TypeConstraint
+ {
+ /// <summary>
+ /// Construct an InstanceOfTypeConstraint for the type provided
+ /// </summary>
+ /// <param name="type">The expected Type</param>
+ public InstanceOfTypeConstraint(Type type)
+ : base(type, "instance of ")
+ {
+ }
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public override string DisplayName { get { return "InstanceOf"; } }
+
+ /// <summary>
+ /// Apply the constraint to an actual value, returning true if it succeeds
+ /// </summary>
+ /// <param name="actual">The actual argument</param>
+ /// <returns>True if the constraint succeeds, otherwise false.</returns>
+ protected override bool Matches(object actual)
+ {
+ return actual != null && expectedType.IsInstanceOfType(actual);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Tests whether a value is less than the value supplied to its constructor
+ /// </summary>
+ public class LessThanConstraint : ComparisonConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LessThanConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The expected value.</param>
+ public LessThanConstraint(object expected) : base(expected, true, false, false, "less than") { }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Tests whether a value is less than or equal to the value supplied to its constructor
+ /// </summary>
+ public class LessThanOrEqualConstraint : ComparisonConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LessThanOrEqualConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The expected value.</param>
+ public LessThanOrEqualConstraint(object expected) : base(expected, true, true, false, "less than or equal to") { }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.IO;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// MessageWriter is the abstract base for classes that write
+ /// constraint descriptions and messages in some form. The
+ /// class has separate methods for writing various components
+ /// of a message, allowing implementations to tailor the
+ /// presentation as needed.
+ /// </summary>
+ public abstract class MessageWriter : StringWriter
+ {
+
+ /// <summary>
+ /// Construct a MessageWriter given a culture
+ /// </summary>
+ protected MessageWriter() : base(System.Globalization.CultureInfo.InvariantCulture) { }
+
+ /// <summary>
+ /// Abstract method to get the max line length
+ /// </summary>
+ public abstract int MaxLineLength { get; set; }
+
+ /// <summary>
+ /// Method to write single line message with optional args, usually
+ /// written to precede the general failure message.
+ /// </summary>
+ /// <param name="message">The message to be written</param>
+ /// <param name="args">Any arguments used in formatting the message</param>
+ public void WriteMessageLine(string message, params object[] args)
+ {
+ WriteMessageLine(0, message, args);
+ }
+
+ /// <summary>
+ /// Method to write single line message with optional args, usually
+ /// written to precede the general failure message, at a givel
+ /// indentation level.
+ /// </summary>
+ /// <param name="level">The indentation level of the message</param>
+ /// <param name="message">The message to be written</param>
+ /// <param name="args">Any arguments used in formatting the message</param>
+ public abstract void WriteMessageLine(int level, string message, params object[] args);
+
+ /// <summary>
+ /// Display Expected and Actual lines for a constraint. This
+ /// is called by MessageWriter's default implementation of
+ /// WriteMessageTo and provides the generic two-line display.
+ /// </summary>
+ /// <param name="result">The failing constraint result</param>
+ public abstract void DisplayDifferences(ConstraintResult result);
+
+ /// <summary>
+ /// Display Expected and Actual lines for given _values. This
+ /// method may be called by constraints that need more control over
+ /// the display of actual and expected _values than is provided
+ /// by the default implementation.
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ /// <param name="actual">The actual value causing the failure</param>
+ public abstract void DisplayDifferences(object expected, object actual);
+
+ /// <summary>
+ /// Display Expected and Actual lines for given _values, including
+ /// a tolerance value on the Expected line.
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ /// <param name="actual">The actual value causing the failure</param>
+ /// <param name="tolerance">The tolerance within which the test was made</param>
+ public abstract void DisplayDifferences(object expected, object actual, Tolerance tolerance);
+
+ /// <summary>
+ /// Display the expected and actual string _values on separate lines.
+ /// If the mismatch parameter is >=0, an additional line is displayed
+ /// line containing a caret that points to the mismatch point.
+ /// </summary>
+ /// <param name="expected">The expected string value</param>
+ /// <param name="actual">The actual string value</param>
+ /// <param name="mismatch">The point at which the strings don't match or -1</param>
+ /// <param name="ignoreCase">If true, case is ignored in locating the point where the strings differ</param>
+ /// <param name="clipping">If true, the strings should be clipped to fit the line</param>
+ public abstract void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping);
+
+ /// <summary>
+ /// Writes the text for an actual value.
+ /// </summary>
+ /// <param name="actual">The actual value.</param>
+ public abstract void WriteActualValue(object actual);
+
+ /// <summary>
+ /// Writes the text for a generalized value.
+ /// </summary>
+ /// <param name="val">The value.</param>
+ public abstract void WriteValue(object val);
+
+ /// <summary>
+ /// Writes the text for a collection value,
+ /// starting at a particular point, to a max length
+ /// </summary>
+ /// <param name="collection">The collection containing elements to write.</param>
+ /// <param name="start">The starting point of the elements to write</param>
+ /// <param name="max">The maximum number of elements to write</param>
+ public abstract void WriteCollectionElements(IEnumerable collection, long start, int max);
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Text;
+using System.Collections;
+using System.Globalization;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Custom value formatter function
+ /// </summary>
+ /// <param name="val">The value</param>
+ /// <returns></returns>
+ public delegate string ValueFormatter(object val);
+
+ /// <summary>
+ /// Custom value formatter factory function
+ /// </summary>
+ /// <param name="next">The next formatter function</param>
+ /// <returns>ValueFormatter</returns>
+ /// <remarks>If the given formatter is unable to handle a certain format, it must call the next formatter in the chain</remarks>
+ public delegate ValueFormatter ValueFormatterFactory(ValueFormatter next);
+
+ /// <summary>
+ /// Static methods used in creating messages
+ /// </summary>
+ internal static class MsgUtils
+ {
+ /// <summary>
+ /// Static string used when strings are clipped
+ /// </summary>
+ private const string ELLIPSIS = "...";
+
+ /// <summary>
+ /// Formatting strings used for expected and actual _values
+ /// </summary>
+ private static readonly string Fmt_Null = "null";
+ private static readonly string Fmt_EmptyString = "<string.Empty>";
+ private static readonly string Fmt_EmptyCollection = "<empty>";
+
+ private static readonly string Fmt_String = "\"{0}\"";
+ private static readonly string Fmt_Char = "'{0}'";
+ private static readonly string Fmt_DateTime = "yyyy-MM-dd HH:mm:ss.fff";
+#if !NETCF
+ private static readonly string Fmt_DateTimeOffset = "yyyy-MM-dd HH:mm:ss.fffzzz";
+#endif
+ private static readonly string Fmt_ValueType = "{0}";
+ private static readonly string Fmt_Default = "<{0}>";
+
+ /// <summary>
+ /// Current head of chain of value formatters. Public for testing.
+ /// </summary>
+ public static ValueFormatter DefaultValueFormatter { get; set; }
+
+ static MsgUtils()
+ {
+ // Initialize formatter to default for values of indeterminate type.
+ DefaultValueFormatter = val => string.Format(Fmt_Default, val);
+
+ AddFormatter(next => val => val is ValueType ? string.Format(Fmt_ValueType, val) : next(val));
+
+ AddFormatter(next => val => val is DateTime ? FormatDateTime((DateTime)val) : next(val));
+
+#if !NETCF
+ AddFormatter(next => val => val is DateTimeOffset ? FormatDateTimeOffset ((DateTimeOffset)val) : next (val));
+#endif
+
+ AddFormatter(next => val => val is decimal ? FormatDecimal((decimal)val) : next(val));
+
+ AddFormatter(next => val => val is float ? FormatFloat((float)val) : next(val));
+
+ AddFormatter(next => val => val is double ? FormatDouble((double)val) : next(val));
+
+ AddFormatter(next => val => val is char ? string.Format(Fmt_Char, val) : next(val));
+
+ AddFormatter(next => val => val is IEnumerable ? FormatCollection((IEnumerable)val, 0, 10) : next(val));
+
+ AddFormatter(next => val => val is string ? FormatString((string)val) : next(val));
+
+ AddFormatter(next => val => val.GetType().IsArray ? FormatArray((Array)val) : next(val));
+
+#if NETCF
+ AddFormatter(next => val =>
+ {
+ var vi = val as System.Reflection.MethodInfo;
+ return (vi != null && vi.IsGenericMethodDefinition)
+ ? string.Format(Fmt_Default, vi.Name + "<>")
+ : next(val);
+ });
+#endif
+ }
+
+ /// <summary>
+ /// Add a formatter to the chain of responsibility.
+ /// </summary>
+ /// <param name="formatterFactory"></param>
+ public static void AddFormatter(ValueFormatterFactory formatterFactory)
+ {
+ DefaultValueFormatter = formatterFactory(DefaultValueFormatter);
+ }
+
+ /// <summary>
+ /// Formats text to represent a generalized value.
+ /// </summary>
+ /// <param name="val">The value</param>
+ /// <returns>The formatted text</returns>
+ public static string FormatValue(object val)
+ {
+ if (val == null)
+ return Fmt_Null;
+
+ var context = TestExecutionContext.CurrentContext;
+
+ if (context != null)
+ return context.CurrentValueFormatter(val);
+ else
+ return DefaultValueFormatter(val);
+ }
+
+ /// <summary>
+ /// Formats text for a collection value,
+ /// starting at a particular point, to a max length
+ /// </summary>
+ /// <param name="collection">The collection containing elements to write.</param>
+ /// <param name="start">The starting point of the elements to write</param>
+ /// <param name="max">The maximum number of elements to write</param>
+ public static string FormatCollection(IEnumerable collection, long start, int max)
+ {
+ int count = 0;
+ int index = 0;
+ System.Text.StringBuilder sb = new System.Text.StringBuilder();
+
+ foreach (object obj in collection)
+ {
+ if (index++ >= start)
+ {
+ if (++count > max)
+ break;
+ sb.Append(count == 1 ? "< " : ", ");
+ sb.Append(FormatValue(obj));
+ }
+ }
+
+ if (count == 0)
+ return Fmt_EmptyCollection;
+
+ if (count > max)
+ sb.Append("...");
+
+ sb.Append(" >");
+
+ return sb.ToString();
+ }
+
+ private static string FormatArray(Array array)
+ {
+ if (array.Length == 0)
+ return Fmt_EmptyCollection;
+
+ int rank = array.Rank;
+ int[] products = new int[rank];
+
+ for (int product = 1, r = rank; --r >= 0; )
+ products[r] = product *= array.GetLength(r);
+
+ int count = 0;
+ System.Text.StringBuilder sb = new System.Text.StringBuilder();
+ foreach (object obj in array)
+ {
+ if (count > 0)
+ sb.Append(", ");
+
+ bool startSegment = false;
+ for (int r = 0; r < rank; r++)
+ {
+ startSegment = startSegment || count % products[r] == 0;
+ if (startSegment) sb.Append("< ");
+ }
+
+ sb.Append(FormatValue(obj));
+
+ ++count;
+
+ bool nextSegment = false;
+ for (int r = 0; r < rank; r++)
+ {
+ nextSegment = nextSegment || count % products[r] == 0;
+ if (nextSegment) sb.Append(" >");
+ }
+ }
+
+ return sb.ToString();
+ }
+
+ private static string FormatString(string s)
+ {
+ return s == string.Empty
+ ? Fmt_EmptyString
+ : string.Format(Fmt_String, s);
+ }
+
+ private static string FormatDouble(double d)
+ {
+
+ if (double.IsNaN(d) || double.IsInfinity(d))
+ return d.ToString();
+ else
+ {
+ string s = d.ToString("G17", CultureInfo.InvariantCulture);
+
+ if (s.IndexOf('.') > 0)
+ return s + "d";
+ else
+ return s + ".0d";
+ }
+ }
+
+ private static string FormatFloat(float f)
+ {
+ if (float.IsNaN(f) || float.IsInfinity(f))
+ return f.ToString();
+ else
+ {
+ string s = f.ToString("G9", CultureInfo.InvariantCulture);
+
+ if (s.IndexOf('.') > 0)
+ return s + "f";
+ else
+ return s + ".0f";
+ }
+ }
+
+ private static string FormatDecimal(Decimal d)
+ {
+ return d.ToString("G29", CultureInfo.InvariantCulture) + "m";
+ }
+
+ private static string FormatDateTime(DateTime dt)
+ {
+ return dt.ToString(Fmt_DateTime, CultureInfo.InvariantCulture);
+ }
+
+#if !NETCF
+ private static string FormatDateTimeOffset(DateTimeOffset dto)
+ {
+ return dto.ToString(Fmt_DateTimeOffset, CultureInfo.InvariantCulture);
+ }
+#endif
+
+ /// <summary>
+ /// Returns the representation of a type as used in NUnitLite.
+ /// This is the same as Type.ToString() except for arrays,
+ /// which are displayed with their declared sizes.
+ /// </summary>
+ /// <param name="obj"></param>
+ /// <returns></returns>
+ public static string GetTypeRepresentation(object obj)
+ {
+ Array array = obj as Array;
+ if (array == null)
+ return string.Format("<{0}>", obj.GetType());
+
+ StringBuilder sb = new StringBuilder();
+ Type elementType = array.GetType();
+ int nest = 0;
+ while (elementType.IsArray)
+ {
+ elementType = elementType.GetElementType();
+ ++nest;
+ }
+ sb.Append(elementType.ToString());
+ sb.Append('[');
+ for (int r = 0; r < array.Rank; r++)
+ {
+ if (r > 0) sb.Append(',');
+ sb.Append(array.GetLength(r));
+ }
+ sb.Append(']');
+
+ while (--nest > 0)
+ sb.Append("[]");
+
+ return string.Format("<{0}>", sb.ToString());
+ }
+ /// <summary>
+ /// Converts any control characters in a string
+ /// to their escaped representation.
+ /// </summary>
+ /// <param name="s">The string to be converted</param>
+ /// <returns>The converted string</returns>
+ public static string EscapeControlChars(string s)
+ {
+ if (s != null)
+ {
+ StringBuilder sb = new StringBuilder();
+
+ foreach (char c in s)
+ {
+ switch (c)
+ {
+ //case '\'':
+ // sb.Append("\\\'");
+ // break;
+ //case '\"':
+ // sb.Append("\\\"");
+ // break;
+ case '\\':
+ sb.Append("\\\\");
+ break;
+ case '\0':
+ sb.Append("\\0");
+ break;
+ case '\a':
+ sb.Append("\\a");
+ break;
+ case '\b':
+ sb.Append("\\b");
+ break;
+ case '\f':
+ sb.Append("\\f");
+ break;
+ case '\n':
+ sb.Append("\\n");
+ break;
+ case '\r':
+ sb.Append("\\r");
+ break;
+ case '\t':
+ sb.Append("\\t");
+ break;
+ case '\v':
+ sb.Append("\\v");
+ break;
+
+ case '\x0085':
+ case '\x2028':
+ case '\x2029':
+ sb.Append(string.Format("\\x{0:X4}", (int)c));
+ break;
+
+ default:
+ sb.Append(c);
+ break;
+ }
+ }
+
+ s = sb.ToString();
+ }
+
+ return s;
+ }
+
+ /// <summary>
+ /// Return the a string representation for a set of indices into an array
+ /// </summary>
+ /// <param name="indices">Array of indices for which a string is needed</param>
+ public static string GetArrayIndicesAsString(int[] indices)
+ {
+ StringBuilder sb = new StringBuilder();
+ sb.Append('[');
+ for (int r = 0; r < indices.Length; r++)
+ {
+ if (r > 0) sb.Append(',');
+ sb.Append(indices[r].ToString());
+ }
+ sb.Append(']');
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// Get an array of indices representing the point in a collection or
+ /// array corresponding to a single int index into the collection.
+ /// </summary>
+ /// <param name="collection">The collection to which the indices apply</param>
+ /// <param name="index">Index in the collection</param>
+ /// <returns>Array of indices</returns>
+ public static int[] GetArrayIndicesFromCollectionIndex(IEnumerable collection, long index)
+ {
+ Array array = collection as Array;
+
+ int rank = array == null ? 1 : array.Rank;
+ int[] result = new int[rank];
+
+ for (int r = rank; --r > 0; )
+ {
+ int l = array.GetLength(r);
+ result[r] = (int)index % l;
+ index /= l;
+ }
+
+ result[0] = (int)index;
+ return result;
+ }
+
+ /// <summary>
+ /// Clip a string to a given length, starting at a particular offset, returning the clipped
+ /// string with ellipses representing the removed parts
+ /// </summary>
+ /// <param name="s">The string to be clipped</param>
+ /// <param name="maxStringLength">The maximum permitted length of the result string</param>
+ /// <param name="clipStart">The point at which to start clipping</param>
+ /// <returns>The clipped string</returns>
+ public static string ClipString(string s, int maxStringLength, int clipStart)
+ {
+ int clipLength = maxStringLength;
+ StringBuilder sb = new StringBuilder();
+
+ if (clipStart > 0)
+ {
+ clipLength -= ELLIPSIS.Length;
+ sb.Append(ELLIPSIS);
+ }
+
+ if (s.Length - clipStart > clipLength)
+ {
+ clipLength -= ELLIPSIS.Length;
+ sb.Append(s.Substring(clipStart, clipLength));
+ sb.Append(ELLIPSIS);
+ }
+ else if (clipStart > 0)
+ sb.Append(s.Substring(clipStart));
+ else
+ sb.Append(s);
+
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// Clip the expected and actual strings in a coordinated fashion,
+ /// so that they may be displayed together.
+ /// </summary>
+ /// <param name="expected"></param>
+ /// <param name="actual"></param>
+ /// <param name="maxDisplayLength"></param>
+ /// <param name="mismatch"></param>
+ public static void ClipExpectedAndActual(ref string expected, ref string actual, int maxDisplayLength, int mismatch)
+ {
+ // Case 1: Both strings fit on line
+ int maxStringLength = Math.Max(expected.Length, actual.Length);
+ if (maxStringLength <= maxDisplayLength)
+ return;
+
+ // Case 2: Assume that the tail of each string fits on line
+ int clipLength = maxDisplayLength - ELLIPSIS.Length;
+ int clipStart = maxStringLength - clipLength;
+
+ // Case 3: If it doesn't, center the mismatch position
+ if (clipStart > mismatch)
+ clipStart = Math.Max(0, mismatch - clipLength / 2);
+
+ expected = ClipString(expected, maxDisplayLength, clipStart);
+ actual = ClipString(actual, maxDisplayLength, clipStart);
+ }
+
+ /// <summary>
+ /// Shows the position two strings start to differ. Comparison
+ /// starts at the start index.
+ /// </summary>
+ /// <param name="expected">The expected string</param>
+ /// <param name="actual">The actual string</param>
+ /// <param name="istart">The index in the strings at which comparison should start</param>
+ /// <param name="ignoreCase">Boolean indicating whether case should be ignored</param>
+ /// <returns>-1 if no mismatch found, or the index where mismatch found</returns>
+ static public int FindMismatchPosition(string expected, string actual, int istart, bool ignoreCase)
+ {
+ int length = Math.Min(expected.Length, actual.Length);
+
+ string s1 = ignoreCase ? expected.ToLower() : expected;
+ string s2 = ignoreCase ? actual.ToLower() : actual;
+
+ for (int i = istart; i < length; i++)
+ {
+ if (s1[i] != s2[i])
+ return i;
+ }
+
+ //
+ // Strings have same content up to the length of the shorter string.
+ // Mismatch occurs because string lengths are different, so show
+ // that they start differing where the shortest string ends
+ //
+ if (expected.Length != actual.Length)
+ return length;
+
+ //
+ // Same strings : We shouldn't get here
+ //
+ return -1;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// NUnitComparer encapsulates NUnit's default behavior
+ /// in comparing two objects.
+ /// </summary>
+ public class NUnitComparer : IComparer
+ {
+ /// <summary>
+ /// Returns the default NUnitComparer.
+ /// </summary>
+ public static NUnitComparer Default
+ {
+ get { return new NUnitComparer(); }
+ }
+
+ /// <summary>
+ /// Compares two objects
+ /// </summary>
+ /// <param name="x"></param>
+ /// <param name="y"></param>
+ /// <returns></returns>
+ public int Compare(object x, object y)
+ {
+ if (x == null)
+ return y == null ? 0 : -1;
+ else if (y == null)
+ return +1;
+
+ if (x is char && y is char)
+ return (char)x == (char)y ? 0 : 1;
+
+ if (Numerics.IsNumericType(x) && Numerics.IsNumericType(y))
+ return Numerics.Compare(x, y);
+
+ if (x is IComparable)
+ return ((IComparable)x).CompareTo(y);
+
+ if (y is IComparable)
+ return -((IComparable)y).CompareTo(x);
+
+ Type xType = x.GetType();
+ Type yType = y.GetType();
+
+ MethodInfo method = xType.GetMethod("CompareTo", new Type[] { yType });
+ if (method != null)
+ return (int)method.Invoke(x, new object[] { y });
+
+ method = yType.GetMethod("CompareTo", new Type[] { xType });
+ if (method != null)
+ return -(int)method.Invoke(y, new object[] { x });
+
+ throw new ArgumentException("Neither value implements IComparable or IComparable<T>");
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.IO;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// NUnitEqualityComparer encapsulates NUnit's handling of
+ /// equality tests between objects.
+ /// </summary>
+ public class NUnitEqualityComparer
+ {
+ #region Static and Instance Fields
+ /// <summary>
+ /// If true, all string comparisons will ignore case
+ /// </summary>
+ private bool caseInsensitive;
+
+ /// <summary>
+ /// If true, arrays will be treated as collections, allowing
+ /// those of different dimensions to be compared
+ /// </summary>
+ private bool compareAsCollection;
+
+ /// <summary>
+ /// Comparison objects used in comparisons for some constraints.
+ /// </summary>
+ private List<EqualityAdapter> externalComparers = new List<EqualityAdapter>();
+
+ /// <summary>
+ /// List of points at which a failure occurred.
+ /// </summary>
+ private List<FailurePoint> failurePoints;
+
+ private static readonly int BUFFER_SIZE = 4096;
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Returns the default NUnitEqualityComparer
+ /// </summary>
+ public static NUnitEqualityComparer Default
+ {
+ get { return new NUnitEqualityComparer(); }
+ }
+ /// <summary>
+ /// Gets and sets a flag indicating whether case should
+ /// be ignored in determining equality.
+ /// </summary>
+ public bool IgnoreCase
+ {
+ get { return caseInsensitive; }
+ set { caseInsensitive = value; }
+ }
+
+ /// <summary>
+ /// Gets and sets a flag indicating that arrays should be
+ /// compared as collections, without regard to their shape.
+ /// </summary>
+ public bool CompareAsCollection
+ {
+ get { return compareAsCollection; }
+ set { compareAsCollection = value; }
+ }
+
+ /// <summary>
+ /// Gets the list of external comparers to be used to
+ /// test for equality. They are applied to members of
+ /// collections, in place of NUnit's own logic.
+ /// </summary>
+ public IList<EqualityAdapter> ExternalComparers
+ {
+ get { return externalComparers; }
+ }
+
+ // TODO: Define some sort of FailurePoint struct or otherwise
+ // eliminate the type-unsafeness of the current approach
+
+ /// <summary>
+ /// Gets the list of failure points for the last Match performed.
+ /// The list consists of objects to be interpreted by the caller.
+ /// This generally means that the caller may only make use of
+ /// objects it has placed on the list at a particular depthy.
+ /// </summary>
+ public IList<FailurePoint> FailurePoints
+ {
+ get { return failurePoints; }
+ }
+
+#if !NETCF
+ /// <summary>
+ /// Flags the comparer to include <see cref="DateTimeOffset.Offset"/>
+ /// property in comparison of two <see cref="DateTimeOffset"/> values.
+ /// </summary>
+ /// <remarks>
+ /// Using this modifier does not allow to use the <see cref="Tolerance"/>
+ /// modifier.
+ /// </remarks>
+ public bool WithSameOffset { get; set; }
+#endif
+ #endregion
+
+ #region Public Methods
+ /// <summary>
+ /// Compares two objects for equality within a tolerance.
+ /// </summary>
+ public bool AreEqual(object x, object y, ref Tolerance tolerance)
+ {
+ this.failurePoints = new List<FailurePoint>();
+
+ if (x == null && y == null)
+ return true;
+
+ if (x == null || y == null)
+ return false;
+
+ if (object.ReferenceEquals(x, y))
+ return true;
+
+ Type xType = x.GetType();
+ Type yType = y.GetType();
+
+ Type xGenericTypeDefinition = xType.GetTypeInfo().IsGenericType ? xType.GetGenericTypeDefinition() : null;
+ Type yGenericTypeDefinition = yType.GetTypeInfo().IsGenericType ? yType.GetGenericTypeDefinition() : null;
+
+ EqualityAdapter externalComparer = GetExternalComparer(x, y);
+ if (externalComparer != null)
+ return externalComparer.AreEqual(x, y);
+
+ if (xType.IsArray && yType.IsArray && !compareAsCollection)
+ return ArraysEqual((Array)x, (Array)y, ref tolerance);
+
+ if (x is IDictionary && y is IDictionary)
+ return DictionariesEqual((IDictionary)x, (IDictionary)y, ref tolerance);
+
+ // Issue #70 - EquivalentTo isn't compatible with IgnoreCase for dictionaries
+ if (x is DictionaryEntry && y is DictionaryEntry)
+ return DictionaryEntriesEqual((DictionaryEntry)x, (DictionaryEntry)y, ref tolerance);
+
+ // IDictionary<,> will eventually try to compare it's key value pairs when using CollectionTally
+ if (xGenericTypeDefinition == typeof(KeyValuePair<,>) &&
+ yGenericTypeDefinition == typeof(KeyValuePair<,>))
+ {
+ var keyTolerance = Tolerance.Exact;
+ object xKey = xType.GetProperty("Key").GetValue(x, null);
+ object yKey = yType.GetProperty("Key").GetValue(y, null);
+ object xValue = xType.GetProperty("Value").GetValue(x, null);
+ object yValue = yType.GetProperty("Value").GetValue(y, null);
+
+ return AreEqual(xKey, yKey, ref keyTolerance) && AreEqual(xValue, yValue, ref tolerance);
+ }
+
+ //if (x is ICollection && y is ICollection)
+ // return CollectionsEqual((ICollection)x, (ICollection)y, ref tolerance);
+
+ if (x is string && y is string)
+ return StringsEqual((string)x, (string)y);
+
+ if (x is Stream && y is Stream)
+ return StreamsEqual((Stream)x, (Stream)y);
+
+ if ( x is char && y is char )
+ return CharsEqual( (char)x, (char)y );
+
+#if !PORTABLE
+ if (x is DirectoryInfo && y is DirectoryInfo)
+ return DirectoriesEqual((DirectoryInfo)x, (DirectoryInfo)y);
+#endif
+
+ if (Numerics.IsNumericType(x) && Numerics.IsNumericType(y))
+ return Numerics.AreEqual(x, y, ref tolerance);
+
+#if !NETCF
+ if (x is DateTimeOffset && y is DateTimeOffset)
+ {
+ bool result;
+
+ DateTimeOffset xAsOffset = (DateTimeOffset)x;
+ DateTimeOffset yAsOffset = (DateTimeOffset)y;
+
+ if (tolerance != null && tolerance.Value is TimeSpan)
+ {
+ TimeSpan amount = (TimeSpan)tolerance.Value;
+ result = (xAsOffset - yAsOffset).Duration() <= amount;
+ }
+ else
+ {
+ result = xAsOffset == yAsOffset;
+ }
+
+ if (result && WithSameOffset)
+ {
+ result = xAsOffset.Offset == yAsOffset.Offset;
+ }
+
+ return result;
+ }
+#endif
+
+ if (tolerance != null && tolerance.Value is TimeSpan)
+ {
+ TimeSpan amount = (TimeSpan)tolerance.Value;
+
+ if (x is DateTime && y is DateTime)
+ return ((DateTime)x - (DateTime)y).Duration() <= amount;
+
+ if (x is TimeSpan && y is TimeSpan)
+ return ((TimeSpan)x - (TimeSpan)y).Duration() <= amount;
+ }
+
+ MethodInfo equals = FirstImplementsIEquatableOfSecond(xType, yType);
+ if (equals != null)
+ return InvokeFirstIEquatableEqualsSecond(x, y, equals);
+ if (xType != yType && (equals = FirstImplementsIEquatableOfSecond(yType, xType)) != null)
+ return InvokeFirstIEquatableEqualsSecond(y, x, equals);
+
+ if (x is IEnumerable && y is IEnumerable)
+ return EnumerablesEqual((IEnumerable) x, (IEnumerable) y, ref tolerance);
+
+ return x.Equals(y);
+ }
+
+ private static MethodInfo FirstImplementsIEquatableOfSecond(Type first, Type second)
+ {
+ var pair = new KeyValuePair<Type, MethodInfo>();
+
+ foreach (var xEquatableArgument in GetEquatableGenericArguments(first))
+ if (xEquatableArgument.Key.IsAssignableFrom(second))
+ if (pair.Key == null || pair.Key.IsAssignableFrom(xEquatableArgument.Key))
+ pair = xEquatableArgument;
+
+ return pair.Value;
+ }
+
+ private static IList<KeyValuePair<Type, MethodInfo>> GetEquatableGenericArguments(Type type)
+ {
+ // NOTE: Original implementation used Array.ConvertAll and
+ // Array.FindAll, which don't exist in the compact framework.
+ var genericArgs = new List<KeyValuePair<Type, MethodInfo>>();
+
+ foreach (Type @interface in type.GetInterfaces())
+ {
+ if (@interface.GetTypeInfo().IsGenericType && @interface.GetGenericTypeDefinition().Equals(typeof(IEquatable<>)))
+ {
+ genericArgs.Add(new KeyValuePair<Type, MethodInfo>(
+ @interface.GetGenericArguments()[0], @interface.GetMethod("Equals")));
+ }
+ }
+
+ return genericArgs;
+ }
+
+ private static bool InvokeFirstIEquatableEqualsSecond(object first, object second, MethodInfo equals)
+ {
+ return equals != null ? (bool)equals.Invoke(first, new object[] { second }) : false;
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ private EqualityAdapter GetExternalComparer(object x, object y)
+ {
+ foreach (EqualityAdapter adapter in externalComparers)
+ if (adapter.CanCompare(x, y))
+ return adapter;
+
+ return null;
+ }
+
+ /// <summary>
+ /// Helper method to compare two arrays
+ /// </summary>
+ private bool ArraysEqual(Array x, Array y, ref Tolerance tolerance)
+ {
+ int rank = x.Rank;
+
+ if (rank != y.Rank)
+ return false;
+
+ for (int r = 1; r < rank; r++)
+ if (x.GetLength(r) != y.GetLength(r))
+ return false;
+
+ return EnumerablesEqual((IEnumerable)x, (IEnumerable)y, ref tolerance);
+ }
+
+ private bool DictionariesEqual(IDictionary x, IDictionary y, ref Tolerance tolerance)
+ {
+ if (x.Count != y.Count)
+ return false;
+
+ CollectionTally tally = new CollectionTally(this, x.Keys);
+ if (!tally.TryRemove(y.Keys) || tally.Count > 0)
+ return false;
+
+ foreach (object key in x.Keys)
+ if (!AreEqual(x[key], y[key], ref tolerance))
+ return false;
+
+ return true;
+ }
+
+ private bool DictionaryEntriesEqual(DictionaryEntry x, DictionaryEntry y, ref Tolerance tolerance)
+ {
+ var keyTolerance = Tolerance.Exact;
+ return AreEqual(x.Key, y.Key, ref keyTolerance) && AreEqual(x.Value, y.Value, ref tolerance);
+ }
+
+ private bool CollectionsEqual(ICollection x, ICollection y, ref Tolerance tolerance)
+ {
+ IEnumerator expectedEnum = null;
+ IEnumerator actualEnum = null;
+
+ try
+ {
+ expectedEnum = x.GetEnumerator();
+ actualEnum = y.GetEnumerator();
+ int count;
+ for (count = 0; ; count++)
+ {
+ bool expectedHasData = expectedEnum.MoveNext();
+ bool actualHasData = actualEnum.MoveNext();
+
+ if (!expectedHasData && !actualHasData)
+ return true;
+
+ if (expectedHasData != actualHasData ||
+ !AreEqual(expectedEnum.Current, actualEnum.Current, ref tolerance))
+ {
+ FailurePoint fp = new FailurePoint();
+ fp.Position = count;
+ fp.ExpectedHasData = expectedHasData;
+ if (expectedHasData)
+ fp.ExpectedValue = expectedEnum.Current;
+ fp.ActualHasData = actualHasData;
+ if (actualHasData)
+ fp.ActualValue = actualEnum.Current;
+ failurePoints.Insert(0, fp);
+ return false;
+ }
+ }
+ }
+ finally
+ {
+ var expectedDisposable = expectedEnum as IDisposable;
+ if (expectedDisposable != null) expectedDisposable.Dispose();
+
+ var actualDisposable = actualEnum as IDisposable;
+ if (actualDisposable != null) actualDisposable.Dispose();
+
+ }
+ }
+
+ private bool StringsEqual(string x, string y)
+ {
+ string s1 = caseInsensitive ? x.ToLower() : x;
+ string s2 = caseInsensitive ? y.ToLower() : y;
+
+ return s1.Equals(s2);
+ }
+
+ private bool CharsEqual(char x, char y)
+ {
+ char c1 = caseInsensitive ? Char.ToLower(x) : x;
+ char c2 = caseInsensitive ? Char.ToLower(y) : y;
+
+ return c1 == c2;
+ }
+
+ private bool EnumerablesEqual(IEnumerable x, IEnumerable y, ref Tolerance tolerance)
+ {
+ IEnumerator expectedEnum = null;
+ IEnumerator actualEnum = null;
+
+ try
+ {
+ expectedEnum = x.GetEnumerator();
+ actualEnum = y.GetEnumerator();
+
+ int count;
+ for (count = 0; ; count++)
+ {
+ bool expectedHasData = expectedEnum.MoveNext();
+ bool actualHasData = actualEnum.MoveNext();
+
+ if (!expectedHasData && !actualHasData)
+ return true;
+
+ if (expectedHasData != actualHasData ||
+ !AreEqual(expectedEnum.Current, actualEnum.Current, ref tolerance))
+ {
+ FailurePoint fp = new FailurePoint();
+ fp.Position = count;
+ fp.ExpectedHasData = expectedHasData;
+ if (expectedHasData)
+ fp.ExpectedValue = expectedEnum.Current;
+ fp.ActualHasData = actualHasData;
+ if (actualHasData)
+ fp.ActualValue = actualEnum.Current;
+ failurePoints.Insert(0, fp);
+ return false;
+ }
+ }
+ }
+ finally
+ {
+ var expectedDisposable = expectedEnum as IDisposable;
+ if (expectedDisposable != null) expectedDisposable.Dispose();
+
+ var actualDisposable = actualEnum as IDisposable;
+ if (actualDisposable != null) actualDisposable.Dispose();
+
+ }
+ }
+
+#if !PORTABLE
+ /// <summary>
+ /// Method to compare two DirectoryInfo objects
+ /// </summary>
+ /// <param name="x">first directory to compare</param>
+ /// <param name="y">second directory to compare</param>
+ /// <returns>true if equivalent, false if not</returns>
+ private static bool DirectoriesEqual(DirectoryInfo x, DirectoryInfo y)
+ {
+ // Do quick compares first
+ if (x.Attributes != y.Attributes ||
+ x.CreationTime != y.CreationTime ||
+ x.LastAccessTime != y.LastAccessTime)
+ {
+ return false;
+ }
+
+ // TODO: Find a cleaner way to do this
+ return new SamePathConstraint(x.FullName).ApplyTo(y.FullName).IsSuccess;
+ }
+#endif
+
+ private bool StreamsEqual(Stream x, Stream y)
+ {
+ if (x == y) return true;
+
+ if (!x.CanRead)
+ throw new ArgumentException("Stream is not readable", "expected");
+ if (!y.CanRead)
+ throw new ArgumentException("Stream is not readable", "actual");
+ if (!x.CanSeek)
+ throw new ArgumentException("Stream is not seekable", "expected");
+ if (!y.CanSeek)
+ throw new ArgumentException("Stream is not seekable", "actual");
+
+ if (x.Length != y.Length) return false;
+
+ byte[] bufferExpected = new byte[BUFFER_SIZE];
+ byte[] bufferActual = new byte[BUFFER_SIZE];
+
+ BinaryReader binaryReaderExpected = new BinaryReader(x);
+ BinaryReader binaryReaderActual = new BinaryReader(y);
+
+ long expectedPosition = x.Position;
+ long actualPosition = y.Position;
+
+ try
+ {
+ binaryReaderExpected.BaseStream.Seek(0, SeekOrigin.Begin);
+ binaryReaderActual.BaseStream.Seek(0, SeekOrigin.Begin);
+
+ for (long readByte = 0; readByte < x.Length; readByte += BUFFER_SIZE)
+ {
+ binaryReaderExpected.Read(bufferExpected, 0, BUFFER_SIZE);
+ binaryReaderActual.Read(bufferActual, 0, BUFFER_SIZE);
+
+ for (int count = 0; count < BUFFER_SIZE; ++count)
+ {
+ if (bufferExpected[count] != bufferActual[count])
+ {
+ FailurePoint fp = new FailurePoint();
+ fp.Position = readByte + count;
+ fp.ExpectedHasData = true;
+ fp.ExpectedValue = bufferExpected[count];
+ fp.ActualHasData = true;
+ fp.ActualValue = bufferActual[count];
+ failurePoints.Insert(0, fp);
+ return false;
+ }
+ }
+ }
+ }
+ finally
+ {
+ x.Position = expectedPosition;
+ y.Position = actualPosition;
+ }
+
+ return true;
+ }
+
+ #endregion
+
+ #region Nested FailurePoint Class
+
+ /// <summary>
+ /// FailurePoint class represents one point of failure
+ /// in an equality test.
+ /// </summary>
+ public class FailurePoint
+ {
+ /// <summary>
+ /// The location of the failure
+ /// </summary>
+ public long Position;
+
+ /// <summary>
+ /// The expected value
+ /// </summary>
+ public object ExpectedValue;
+
+ /// <summary>
+ /// The actual value
+ /// </summary>
+ public object ActualValue;
+
+ /// <summary>
+ /// Indicates whether the expected value is valid
+ /// </summary>
+ public bool ExpectedHasData;
+
+ /// <summary>
+ /// Indicates whether the actual value is valid
+ /// </summary>
+ public bool ActualHasData;
+ }
+
+ #endregion
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// NaNConstraint tests that the actual value is a double or float NaN
+ /// </summary>
+ public class NaNConstraint : Constraint
+ {
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "NaN"; }
+ }
+
+ /// <summary>
+ /// Test that the actual value is an NaN
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ return new ConstraintResult(this, actual,
+ actual is double && double.IsNaN((double)(object)actual) ||
+ actual is float && float.IsNaN((float)(object)actual));
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// NoItemConstraint applies another constraint to each
+ /// item in a collection, failing if any of them succeeds.
+ /// </summary>
+ public class NoItemConstraint : PrefixConstraint
+ {
+ /// <summary>
+ /// Construct a SomeItemsConstraint on top of an existing constraint
+ /// </summary>
+ /// <param name="itemConstraint"></param>
+ public NoItemConstraint(IConstraint itemConstraint)
+ : base(itemConstraint)
+ {
+ DescriptionPrefix = "no item";
+ }
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public override string DisplayName { get { return "None"; } }
+
+ /// <summary>
+ /// Apply the item constraint to each item in the collection,
+ /// failing if any item fails.
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ if (!(actual is IEnumerable))
+ throw new ArgumentException("The actual value must be an IEnumerable", "actual");
+
+ foreach (object item in (IEnumerable)actual)
+ if (BaseConstraint.ApplyTo(item).IsSuccess)
+ return new ConstraintResult(this, actual, ConstraintStatus.Failure);
+
+ return new ConstraintResult(this, actual, ConstraintStatus.Success);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// NotConstraint negates the effect of some other constraint
+ /// </summary>
+ public class NotConstraint : PrefixConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NotConstraint"/> class.
+ /// </summary>
+ /// <param name="baseConstraint">The base constraint to be negated.</param>
+ public NotConstraint(IConstraint baseConstraint)
+ : base(baseConstraint)
+ {
+ this.DescriptionPrefix = "not";
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for if the base constraint fails, false if it succeeds</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ var baseResult = BaseConstraint.ApplyTo(actual);
+ return new ConstraintResult(this, baseResult.ActualValue, !baseResult.IsSuccess);
+ }
+
+ // TODO: May need a special result type
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// NullConstraint tests that the actual value is null
+ /// </summary>
+ public class NullConstraint : Constraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NullConstraint"/> class.
+ /// </summary>
+ public NullConstraint()
+ {
+ this.Description = "null";
+ }
+
+ /// <summary>
+ /// Applies the constraint to an actual value, returning a ConstraintResult.
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>A ConstraintResult</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ return new ConstraintResult(this, actual, actual == null);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// The Numerics class contains common operations on numeric _values.
+ /// </summary>
+ public class Numerics
+ {
+ #region Numeric Type Recognition
+ /// <summary>
+ /// Checks the type of the object, returning true if
+ /// the object is a numeric type.
+ /// </summary>
+ /// <param name="obj">The object to check</param>
+ /// <returns>true if the object is a numeric type</returns>
+ public static bool IsNumericType(Object obj)
+ {
+ return IsFloatingPointNumeric(obj) || IsFixedPointNumeric(obj);
+ }
+
+ /// <summary>
+ /// Checks the type of the object, returning true if
+ /// the object is a floating point numeric type.
+ /// </summary>
+ /// <param name="obj">The object to check</param>
+ /// <returns>true if the object is a floating point numeric type</returns>
+ public static bool IsFloatingPointNumeric(Object obj)
+ {
+ if (null != obj)
+ {
+ if (obj is System.Double) return true;
+ if (obj is System.Single) return true;
+ }
+ return false;
+ }
+ /// <summary>
+ /// Checks the type of the object, returning true if
+ /// the object is a fixed point numeric type.
+ /// </summary>
+ /// <param name="obj">The object to check</param>
+ /// <returns>true if the object is a fixed point numeric type</returns>
+ public static bool IsFixedPointNumeric(Object obj)
+ {
+ if (null != obj)
+ {
+ if (obj is System.Byte) return true;
+ if (obj is System.SByte) return true;
+ if (obj is System.Decimal) return true;
+ if (obj is System.Int32) return true;
+ if (obj is System.UInt32) return true;
+ if (obj is System.Int64) return true;
+ if (obj is System.UInt64) return true;
+ if (obj is System.Int16) return true;
+ if (obj is System.UInt16) return true;
+ if (obj is System.Char) return true;
+ }
+ return false;
+ }
+ #endregion
+
+ #region Numeric Equality
+ /// <summary>
+ /// Test two numeric _values for equality, performing the usual numeric
+ /// conversions and using a provided or default tolerance. If the tolerance
+ /// provided is Empty, this method may set it to a default tolerance.
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ /// <param name="actual">The actual value</param>
+ /// <param name="tolerance">A reference to the tolerance in effect</param>
+ /// <returns>True if the _values are equal</returns>
+ public static bool AreEqual(object expected, object actual, ref Tolerance tolerance)
+ {
+ if (expected is double || actual is double)
+ return AreEqual(Convert.ToDouble(expected), Convert.ToDouble(actual), ref tolerance);
+
+ if (expected is float || actual is float)
+ return AreEqual(Convert.ToSingle(expected), Convert.ToSingle(actual), ref tolerance);
+
+ if (tolerance.Mode == ToleranceMode.Ulps)
+ throw new InvalidOperationException("Ulps may only be specified for floating point arguments");
+
+ if (expected is decimal || actual is decimal)
+ return AreEqual(Convert.ToDecimal(expected), Convert.ToDecimal(actual), tolerance);
+
+ if (expected is ulong || actual is ulong)
+ return AreEqual(Convert.ToUInt64(expected), Convert.ToUInt64(actual), tolerance);
+
+ if (expected is long || actual is long)
+ return AreEqual(Convert.ToInt64(expected), Convert.ToInt64(actual), tolerance);
+
+ if (expected is uint || actual is uint)
+ return AreEqual(Convert.ToUInt32(expected), Convert.ToUInt32(actual), tolerance);
+
+ return AreEqual(Convert.ToInt32(expected), Convert.ToInt32(actual), tolerance);
+ }
+
+ private static bool AreEqual(double expected, double actual, ref Tolerance tolerance)
+ {
+ if (double.IsNaN(expected) && double.IsNaN(actual))
+ return true;
+
+ // Handle infinity specially since subtracting two infinite _values gives
+ // NaN and the following test fails. mono also needs NaN to be handled
+ // specially although ms.net could use either method. Also, handle
+ // situation where no tolerance is used.
+ if (double.IsInfinity(expected) || double.IsNaN(expected) || double.IsNaN(actual))
+ {
+ return expected.Equals(actual);
+ }
+
+ if (tolerance.IsUnsetOrDefault && GlobalSettings.DefaultFloatingPointTolerance > 0.0d)
+ tolerance = new Tolerance(GlobalSettings.DefaultFloatingPointTolerance);
+
+ switch (tolerance.Mode)
+ {
+ case ToleranceMode.Unset:
+ return expected.Equals(actual);
+
+ case ToleranceMode.Linear:
+ return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value);
+
+ case ToleranceMode.Percent:
+ if (expected == 0.0)
+ return expected.Equals(actual);
+
+ double relativeError = Math.Abs((expected - actual) / expected);
+ return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0);
+
+ case ToleranceMode.Ulps:
+ return FloatingPointNumerics.AreAlmostEqualUlps(
+ expected, actual, Convert.ToInt64(tolerance.Value));
+
+ default:
+ throw new ArgumentException("Unknown tolerance mode specified", "mode");
+ }
+ }
+
+ private static bool AreEqual(float expected, float actual, ref Tolerance tolerance)
+ {
+ if (float.IsNaN(expected) && float.IsNaN(actual))
+ return true;
+
+ // handle infinity specially since subtracting two infinite _values gives
+ // NaN and the following test fails. mono also needs NaN to be handled
+ // specially although ms.net could use either method.
+ if (float.IsInfinity(expected) || float.IsNaN(expected) || float.IsNaN(actual))
+ {
+ return expected.Equals(actual);
+ }
+
+ if (tolerance.IsUnsetOrDefault && GlobalSettings.DefaultFloatingPointTolerance > 0.0d)
+ tolerance = new Tolerance(GlobalSettings.DefaultFloatingPointTolerance);
+
+ switch (tolerance.Mode)
+ {
+ case ToleranceMode.Unset:
+ return expected.Equals(actual);
+
+ case ToleranceMode.Linear:
+ return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value);
+
+ case ToleranceMode.Percent:
+ if (expected == 0.0f)
+ return expected.Equals(actual);
+ float relativeError = Math.Abs((expected - actual) / expected);
+ return (relativeError <= Convert.ToSingle(tolerance.Value) / 100.0f);
+
+ case ToleranceMode.Ulps:
+ return FloatingPointNumerics.AreAlmostEqualUlps(
+ expected, actual, Convert.ToInt32(tolerance.Value));
+
+ default:
+ throw new ArgumentException("Unknown tolerance mode specified", "mode");
+ }
+ }
+
+
+ private static bool AreEqual(decimal expected, decimal actual, Tolerance tolerance)
+ {
+ switch (tolerance.Mode)
+ {
+ case ToleranceMode.Unset:
+ return expected.Equals(actual);
+
+ case ToleranceMode.Linear:
+ decimal decimalTolerance = Convert.ToDecimal(tolerance.Value);
+ if (decimalTolerance > 0m)
+ return Math.Abs(expected - actual) <= decimalTolerance;
+
+ return expected.Equals(actual);
+
+ case ToleranceMode.Percent:
+ if (expected == 0m)
+ return expected.Equals(actual);
+
+ double relativeError = Math.Abs(
+ (double)(expected - actual) / (double)expected);
+ return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0);
+
+ default:
+ throw new ArgumentException("Unknown tolerance mode specified", "mode");
+ }
+ }
+
+ private static bool AreEqual(ulong expected, ulong actual, Tolerance tolerance)
+ {
+ switch (tolerance.Mode)
+ {
+ case ToleranceMode.Unset:
+ return expected.Equals(actual);
+
+ case ToleranceMode.Linear:
+ ulong ulongTolerance = Convert.ToUInt64(tolerance.Value);
+ if (ulongTolerance > 0ul)
+ {
+ ulong diff = expected >= actual ? expected - actual : actual - expected;
+ return diff <= ulongTolerance;
+ }
+
+ return expected.Equals(actual);
+
+ case ToleranceMode.Percent:
+ if (expected == 0ul)
+ return expected.Equals(actual);
+
+ // Can't do a simple Math.Abs() here since it's unsigned
+ ulong difference = Math.Max(expected, actual) - Math.Min(expected, actual);
+ double relativeError = Math.Abs((double)difference / (double)expected);
+ return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0);
+
+ default:
+ throw new ArgumentException("Unknown tolerance mode specified", "mode");
+ }
+ }
+
+ private static bool AreEqual(long expected, long actual, Tolerance tolerance)
+ {
+ switch (tolerance.Mode)
+ {
+ case ToleranceMode.Unset:
+ return expected.Equals(actual);
+
+ case ToleranceMode.Linear:
+ long longTolerance = Convert.ToInt64(tolerance.Value);
+ if (longTolerance > 0L)
+ return Math.Abs(expected - actual) <= longTolerance;
+
+ return expected.Equals(actual);
+
+ case ToleranceMode.Percent:
+ if (expected == 0L)
+ return expected.Equals(actual);
+
+ double relativeError = Math.Abs(
+ (double)(expected - actual) / (double)expected);
+ return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0);
+
+ default:
+ throw new ArgumentException("Unknown tolerance mode specified", "mode");
+ }
+ }
+
+ private static bool AreEqual(uint expected, uint actual, Tolerance tolerance)
+ {
+ switch (tolerance.Mode)
+ {
+ case ToleranceMode.Unset:
+ return expected.Equals(actual);
+
+ case ToleranceMode.Linear:
+ uint uintTolerance = Convert.ToUInt32(tolerance.Value);
+ if (uintTolerance > 0)
+ {
+ uint diff = expected >= actual ? expected - actual : actual - expected;
+ return diff <= uintTolerance;
+ }
+
+ return expected.Equals(actual);
+
+ case ToleranceMode.Percent:
+ if (expected == 0u)
+ return expected.Equals(actual);
+
+ // Can't do a simple Math.Abs() here since it's unsigned
+ uint difference = Math.Max(expected, actual) - Math.Min(expected, actual);
+ double relativeError = Math.Abs((double)difference / (double)expected);
+ return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0);
+
+ default:
+ throw new ArgumentException("Unknown tolerance mode specified", "mode");
+ }
+ }
+
+ private static bool AreEqual(int expected, int actual, Tolerance tolerance)
+ {
+ switch (tolerance.Mode)
+ {
+ case ToleranceMode.Unset:
+ return expected.Equals(actual);
+
+ case ToleranceMode.Linear:
+ int intTolerance = Convert.ToInt32(tolerance.Value);
+ if (intTolerance > 0)
+ return Math.Abs(expected - actual) <= intTolerance;
+
+ return expected.Equals(actual);
+
+ case ToleranceMode.Percent:
+ if (expected == 0)
+ return expected.Equals(actual);
+
+ double relativeError = Math.Abs(
+ (double)(expected - actual) / (double)expected);
+ return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0);
+
+ default:
+ throw new ArgumentException("Unknown tolerance mode specified", "mode");
+ }
+ }
+ #endregion
+
+ #region Numeric Comparisons
+ /// <summary>
+ /// Compare two numeric _values, performing the usual numeric conversions.
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ /// <param name="actual">The actual value</param>
+ /// <returns>The relationship of the _values to each other</returns>
+ public static int Compare(object expected, object actual)
+ {
+ if (!IsNumericType(expected) || !IsNumericType(actual))
+ throw new ArgumentException("Both arguments must be numeric");
+
+ if (IsFloatingPointNumeric(expected) || IsFloatingPointNumeric(actual))
+ return Convert.ToDouble(expected).CompareTo(Convert.ToDouble(actual));
+
+ if (expected is decimal || actual is decimal)
+ return Convert.ToDecimal(expected).CompareTo(Convert.ToDecimal(actual));
+
+ if (expected is ulong || actual is ulong)
+ return Convert.ToUInt64(expected).CompareTo(Convert.ToUInt64(actual));
+
+ if (expected is long || actual is long)
+ return Convert.ToInt64(expected).CompareTo(Convert.ToInt64(actual));
+
+ if (expected is uint || actual is uint)
+ return Convert.ToUInt32(expected).CompareTo(Convert.ToUInt32(actual));
+
+ return Convert.ToInt32(expected).CompareTo(Convert.ToInt32(actual));
+ }
+ #endregion
+
+ private Numerics()
+ {
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Represents a constraint that succeeds if all the
+ /// members of a collection match a base constraint.
+ /// </summary>
+ public class AllOperator : CollectionOperator
+ {
+ /// <summary>
+ /// Returns a constraint that will apply the argument
+ /// to the members of a collection, succeeding if
+ /// they all succeed.
+ /// </summary>
+ public override IConstraint ApplyPrefix(IConstraint constraint)
+ {
+ return new AllItemsConstraint(constraint);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Operator that requires both it's arguments to succeed
+ /// </summary>
+ public class AndOperator : BinaryOperator
+ {
+ /// <summary>
+ /// Construct an AndOperator
+ /// </summary>
+ public AndOperator()
+ {
+ this.left_precedence = this.right_precedence = 2;
+ }
+
+ /// <summary>
+ /// Apply the operator to produce an AndConstraint
+ /// </summary>
+ public override IConstraint ApplyOperator(IConstraint left, IConstraint right)
+ {
+ return new AndConstraint(left, right);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Operator that tests for the presence of a particular attribute
+ /// on a type and optionally applies further tests to the attribute.
+ /// </summary>
+ public class AttributeOperator : SelfResolvingOperator
+ {
+ private readonly Type type;
+
+ /// <summary>
+ /// Construct an AttributeOperator for a particular Type
+ /// </summary>
+ /// <param name="type">The Type of attribute tested</param>
+ public AttributeOperator(Type type)
+ {
+ this.type = type;
+
+ // Attribute stacks on anything and allows only
+ // prefix operators to stack on it.
+ this.left_precedence = this.right_precedence = 1;
+ }
+
+ /// <summary>
+ /// Reduce produces a constraint from the operator and
+ /// any arguments. It takes the arguments from the constraint
+ /// stack and pushes the resulting constraint on it.
+ /// </summary>
+ public override void Reduce(ConstraintBuilder.ConstraintStack stack)
+ {
+ if (RightContext == null || RightContext is BinaryOperator)
+ stack.Push(new AttributeExistsConstraint(type));
+ else
+ stack.Push(new AttributeConstraint(type, stack.Pop()));
+ }
+ }
+ }
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Abstract base class for all binary operators
+ /// </summary>
+ public abstract class BinaryOperator : ConstraintOperator
+ {
+ /// <summary>
+ /// Reduce produces a constraint from the operator and
+ /// any arguments. It takes the arguments from the constraint
+ /// stack and pushes the resulting constraint on it.
+ /// </summary>
+ /// <param name="stack"></param>
+ public override void Reduce(ConstraintBuilder.ConstraintStack stack)
+ {
+ IConstraint right = stack.Pop();
+ IConstraint left = stack.Pop();
+ stack.Push(ApplyOperator(left, right));
+ }
+
+ /// <summary>
+ /// Gets the left precedence of the operator
+ /// </summary>
+ public override int LeftPrecedence
+ {
+ get
+ {
+ return RightContext is CollectionOperator
+ ? base.LeftPrecedence + 10
+ : base.LeftPrecedence;
+ }
+ }
+
+ /// <summary>
+ /// Gets the right precedence of the operator
+ /// </summary>
+ public override int RightPrecedence
+ {
+ get
+ {
+ return RightContext is CollectionOperator
+ ? base.RightPrecedence + 10
+ : base.RightPrecedence;
+ }
+ }
+
+ /// <summary>
+ /// Abstract method that produces a constraint by applying
+ /// the operator to its left and right constraint arguments.
+ /// </summary>
+ public abstract IConstraint ApplyOperator(IConstraint left, IConstraint right);
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Abstract base for operators that indicate how to
+ /// apply a constraint to items in a collection.
+ /// </summary>
+ public abstract class CollectionOperator : PrefixOperator
+ {
+ /// <summary>
+ /// Constructs a CollectionOperator
+ /// </summary>
+ protected CollectionOperator()
+ {
+ // Collection Operators stack on everything
+ // and allow all other ops to stack on them
+ this.left_precedence = 1;
+ this.right_precedence = 10;
+ }
+ }
+ }
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// The ConstraintOperator class is used internally by a
+ /// ConstraintBuilder to represent an operator that
+ /// modifies or combines constraints.
+ ///
+ /// Constraint operators use left and right precedence
+ /// _values to determine whether the top operator on the
+ /// stack should be reduced before pushing a new operator.
+ /// </summary>
+ public abstract class ConstraintOperator
+ {
+ private object leftContext;
+ private object rightContext;
+
+ /// <summary>
+ /// The precedence value used when the operator
+ /// is about to be pushed to the stack.
+ /// </summary>
+ protected int left_precedence;
+
+ /// <summary>
+ /// The precedence value used when the operator
+ /// is on the top of the stack.
+ /// </summary>
+ protected int right_precedence;
+
+ /// <summary>
+ /// The syntax element preceding this operator
+ /// </summary>
+ public object LeftContext
+ {
+ get { return leftContext; }
+ set { leftContext = value; }
+ }
+
+ /// <summary>
+ /// The syntax element following this operator
+ /// </summary>
+ public object RightContext
+ {
+ get { return rightContext; }
+ set { rightContext = value; }
+ }
+
+ /// <summary>
+ /// The precedence value used when the operator
+ /// is about to be pushed to the stack.
+ /// </summary>
+ public virtual int LeftPrecedence
+ {
+ get { return left_precedence; }
+ }
+
+ /// <summary>
+ /// The precedence value used when the operator
+ /// is on the top of the stack.
+ /// </summary>
+ public virtual int RightPrecedence
+ {
+ get { return right_precedence; }
+ }
+
+ /// <summary>
+ /// Reduce produces a constraint from the operator and
+ /// any arguments. It takes the arguments from the constraint
+ /// stack and pushes the resulting constraint on it.
+ /// </summary>
+ /// <param name="stack"></param>
+ public abstract void Reduce(ConstraintBuilder.ConstraintStack stack);
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Represents a constraint that succeeds if the specified
+ /// count of members of a collection match a base constraint.
+ /// </summary>
+ public class ExactCountOperator : CollectionOperator
+ {
+ private int expectedCount;
+
+ /// <summary>
+ /// Construct an ExactCountOperator for a specified count
+ /// </summary>
+ /// <param name="expectedCount">The expected count</param>
+ public ExactCountOperator(int expectedCount)
+ {
+ this.expectedCount = expectedCount;
+ }
+
+ /// <summary>
+ /// Returns a constraint that will apply the argument
+ /// to the members of a collection, succeeding if
+ /// none of them succeed.
+ /// </summary>
+ public override IConstraint ApplyPrefix(IConstraint constraint)
+ {
+ return new ExactCountConstraint(expectedCount, constraint);
+ }
+ }
+}
+
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Represents a constraint that succeeds if none of the
+ /// members of a collection match a base constraint.
+ /// </summary>
+ public class NoneOperator : CollectionOperator
+ {
+ /// <summary>
+ /// Returns a constraint that will apply the argument
+ /// to the members of a collection, succeeding if
+ /// none of them succeed.
+ /// </summary>
+ public override IConstraint ApplyPrefix(IConstraint constraint)
+ {
+ return new NoItemConstraint(constraint);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Negates the test of the constraint it wraps.
+ /// </summary>
+ public class NotOperator : PrefixOperator
+ {
+ /// <summary>
+ /// Constructs a new NotOperator
+ /// </summary>
+ public NotOperator()
+ {
+ // Not stacks on anything and only allows other
+ // prefix ops to stack on top of it.
+ this.left_precedence = this.right_precedence = 1;
+ }
+
+ /// <summary>
+ /// Returns a NotConstraint applied to its argument.
+ /// </summary>
+ public override IConstraint ApplyPrefix(IConstraint constraint)
+ {
+ return new NotConstraint(constraint);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Operator that requires at least one of it's arguments to succeed
+ /// </summary>
+ public class OrOperator : BinaryOperator
+ {
+ /// <summary>
+ /// Construct an OrOperator
+ /// </summary>
+ public OrOperator()
+ {
+ this.left_precedence = this.right_precedence = 3;
+ }
+
+ /// <summary>
+ /// Apply the operator to produce an OrConstraint
+ /// </summary>
+ public override IConstraint ApplyOperator(IConstraint left, IConstraint right)
+ {
+ return new OrConstraint(left, right);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// PrefixOperator takes a single constraint and modifies
+ /// it's action in some way.
+ /// </summary>
+ public abstract class PrefixOperator : ConstraintOperator
+ {
+ /// <summary>
+ /// Reduce produces a constraint from the operator and
+ /// any arguments. It takes the arguments from the constraint
+ /// stack and pushes the resulting constraint on it.
+ /// </summary>
+ /// <param name="stack"></param>
+ public override void Reduce(ConstraintBuilder.ConstraintStack stack)
+ {
+ stack.Push(ApplyPrefix(stack.Pop()));
+ }
+
+ /// <summary>
+ /// Returns the constraint created by applying this
+ /// prefix to another constraint.
+ /// </summary>
+ /// <param name="constraint"></param>
+ /// <returns></returns>
+ public abstract IConstraint ApplyPrefix(IConstraint constraint);
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Operator used to test for the presence of a named Property
+ /// on an object and optionally apply further tests to the
+ /// value of that property.
+ /// </summary>
+ public class PropOperator : SelfResolvingOperator
+ {
+ private readonly string name;
+
+ /// <summary>
+ /// Gets the name of the property to which the operator applies
+ /// </summary>
+ public string Name
+ {
+ get { return name; }
+ }
+
+ /// <summary>
+ /// Constructs a PropOperator for a particular named property
+ /// </summary>
+ public PropOperator(string name)
+ {
+ this.name = name;
+
+ // Prop stacks on anything and allows only
+ // prefix operators to stack on it.
+ this.left_precedence = this.right_precedence = 1;
+ }
+
+ /// <summary>
+ /// Reduce produces a constraint from the operator and
+ /// any arguments. It takes the arguments from the constraint
+ /// stack and pushes the resulting constraint on it.
+ /// </summary>
+ /// <param name="stack"></param>
+ public override void Reduce(ConstraintBuilder.ConstraintStack stack)
+ {
+ if (RightContext == null || RightContext is BinaryOperator)
+ stack.Push(new PropertyExistsConstraint(name));
+ else
+ stack.Push(new PropertyConstraint(name, stack.Pop()));
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Abstract base class for operators that are able to reduce to a
+ /// constraint whether or not another syntactic element follows.
+ /// </summary>
+ public abstract class SelfResolvingOperator : ConstraintOperator
+ {
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Represents a constraint that succeeds if any of the
+ /// members of a collection match a base constraint.
+ /// </summary>
+ public class SomeOperator : CollectionOperator
+ {
+ /// <summary>
+ /// Returns a constraint that will apply the argument
+ /// to the members of a collection, succeeding if
+ /// any of them succeed.
+ /// </summary>
+ public override IConstraint ApplyPrefix(IConstraint constraint)
+ {
+ return new SomeItemsConstraint(constraint);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Operator that tests that an exception is thrown and
+ /// optionally applies further tests to the exception.
+ /// </summary>
+ public class ThrowsOperator : SelfResolvingOperator
+ {
+ /// <summary>
+ /// Construct a ThrowsOperator
+ /// </summary>
+ public ThrowsOperator()
+ {
+ // ThrowsOperator stacks on everything but
+ // it's always the first item on the stack
+ // anyway. It is evaluated last of all ops.
+ this.left_precedence = 1;
+ this.right_precedence = 100;
+ }
+
+ /// <summary>
+ /// Reduce produces a constraint from the operator and
+ /// any arguments. It takes the arguments from the constraint
+ /// stack and pushes the resulting constraint on it.
+ /// </summary>
+ public override void Reduce(ConstraintBuilder.ConstraintStack stack)
+ {
+ if (RightContext == null || RightContext is BinaryOperator)
+ stack.Push(new ThrowsExceptionConstraint());
+ else
+ stack.Push(new ThrowsConstraint(stack.Pop()));
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Represents a constraint that simply wraps the
+ /// constraint provided as an argument, without any
+ /// further functionality, but which modifies the
+ /// order of evaluation because of its precedence.
+ /// </summary>
+ public class WithOperator : PrefixOperator
+ {
+ /// <summary>
+ /// Constructor for the WithOperator
+ /// </summary>
+ public WithOperator()
+ {
+ this.left_precedence = 1;
+ this.right_precedence = 4;
+ }
+
+ /// <summary>
+ /// Returns a constraint that wraps its argument
+ /// </summary>
+ public override IConstraint ApplyPrefix(IConstraint constraint)
+ {
+ return constraint;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// OrConstraint succeeds if either member succeeds
+ /// </summary>
+ public class OrConstraint : BinaryConstraint
+ {
+ /// <summary>
+ /// Create an OrConstraint from two other constraints
+ /// </summary>
+ /// <param name="left">The first constraint</param>
+ /// <param name="right">The second constraint</param>
+ public OrConstraint(IConstraint left, IConstraint right) : base(left, right) { }
+
+ /// <summary>
+ /// Gets text describing a constraint
+ /// </summary>
+ public override string Description
+ {
+ get { return Left.Description + " or " + Right.Description; }
+ }
+
+ /// <summary>
+ /// Apply the member constraints to an actual value, succeeding
+ /// succeeding as soon as one of them succeeds.
+ /// </summary>
+ /// <param name="actual">The actual value</param>
+ /// <returns>True if either constraint succeeded</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ bool hasSucceeded = Left.ApplyTo(actual).IsSuccess || Right.ApplyTo(actual).IsSuccess;
+ return new ConstraintResult(this, actual, hasSucceeded);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !PORTABLE
+using System;
+using System.IO;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework.Constraints
+{
+#region PathConstraint
+ /// <summary>
+ /// PathConstraint serves as the abstract base of constraints
+ /// that operate on paths and provides several helper methods.
+ /// </summary>
+ public abstract class PathConstraint : StringConstraint
+ {
+ private const char WindowsDirectorySeparatorChar = '\\';
+ private const char NonWindowsDirectorySeparatorChar = '/';
+ private static readonly char[] DirectorySeparatorChars = new char[] { WindowsDirectorySeparatorChar, NonWindowsDirectorySeparatorChar };
+
+ /// <summary>
+ /// Construct a PathConstraint for a give expected path
+ /// </summary>
+ /// <param name="expected">The expected path</param>
+ protected PathConstraint(string expected)
+ : base(expected)
+ {
+ this.expected = expected;
+ this.caseInsensitive = Path.DirectorySeparatorChar == WindowsDirectorySeparatorChar;
+ }
+
+ /// <summary>
+ /// Modifies the current instance to be case-sensitive
+ /// and returns it.
+ /// </summary>
+ public PathConstraint RespectCase
+ {
+ get { caseInsensitive = false; return this; }
+ }
+
+ /// <summary>
+ /// Returns the string representation of this constraint
+ /// </summary>
+ protected override string GetStringRepresentation()
+ {
+ return string.Format("<{0} \"{1}\" {2}>", DisplayName.ToLower(), expected, caseInsensitive ? "ignorecase" : "respectcase");
+ }
+
+#region Helper Methods
+ /// <summary>
+ /// Canonicalize the provided path
+ /// </summary>
+ /// <param name="path"></param>
+ /// <returns>The path in standardized form</returns>
+ protected string Canonicalize(string path)
+ {
+ if (Path.DirectorySeparatorChar != Path.AltDirectorySeparatorChar)
+ path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
+
+ string leadingSeparators = "";
+
+ foreach (char c in path)
+ {
+ if (c == WindowsDirectorySeparatorChar || c == NonWindowsDirectorySeparatorChar)
+ {
+ leadingSeparators += Path.DirectorySeparatorChar;
+ }
+ else break;
+ }
+
+#if !NETCF
+ string[] parts = path.Split(DirectorySeparatorChars, StringSplitOptions.RemoveEmptyEntries);
+#else
+ string[] parts = path.Split(DirectorySeparatorChars);
+#endif
+
+ int count = 0;
+ bool shifting = false;
+ foreach (string part in parts)
+ {
+ switch (part)
+ {
+ case ".":
+ case "":
+ shifting = true;
+ break;
+
+ case "..":
+ shifting = true;
+ if (count > 0)
+ --count;
+ break;
+ default:
+ if (shifting)
+ parts[count] = part;
+ ++count;
+ break;
+ }
+ }
+
+ return leadingSeparators + String.Join(Path.DirectorySeparatorChar.ToString(), parts, 0, count);
+ }
+
+ /// <summary>
+ /// Test whether one path in canonical form is a subpath of another path
+ /// </summary>
+ /// <param name="path1">The first path - supposed to be the parent path</param>
+ /// <param name="path2">The second path - supposed to be the child path</param>
+ /// <returns></returns>
+ protected bool IsSubPath(string path1, string path2)
+ {
+ int length1 = path1.Length;
+ int length2 = path2.Length;
+
+ // if path1 is longer or equal, then path2 can't be a subpath
+ if (length1 >= length2)
+ return false;
+
+ // path 2 is longer than path 1: see if initial parts match
+ if (!StringUtil.StringsEqual(path1, path2.Substring(0, length1), caseInsensitive))
+ return false;
+
+ // must match through or up to a directory separator boundary
+ return path2[length1 - 1] == Path.DirectorySeparatorChar ||
+ path2[length1] == Path.DirectorySeparatorChar;
+ }
+
+#endregion
+ }
+#endregion
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Predicate constraint wraps a Predicate in a constraint,
+ /// returning success if the predicate is true.
+ /// </summary>
+ public class PredicateConstraint<T> : Constraint
+ {
+ readonly Predicate<T> predicate;
+
+ /// <summary>
+ /// Construct a PredicateConstraint from a predicate
+ /// </summary>
+ public PredicateConstraint(Predicate<T> predicate)
+ {
+ this.predicate = predicate;
+ }
+
+ /// <summary>
+ /// Gets text describing a constraint
+ /// </summary>
+ public override string Description
+ {
+ get
+ {
+#if PORTABLE
+ var name = predicate.GetMethodInfo().Name;
+#else
+ var name = predicate.Method.Name;
+#endif
+ return name.StartsWith("<")
+ ? "value matching lambda expression"
+ : "value matching " + name;
+ }
+ }
+
+ /// <summary>
+ /// Determines whether the predicate succeeds when applied
+ /// to the actual value.
+ /// </summary>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ if (!(actual is T))
+ throw new ArgumentException("The actual value is not of type " + typeof(T).Name, "actual");
+
+ return new ConstraintResult(this, actual, predicate((T)(object)actual));
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Abstract base class used for prefixes
+ /// </summary>
+ public abstract class PrefixConstraint : Constraint
+ {
+ /// <summary>
+ /// The base constraint
+ /// </summary>
+ protected IConstraint BaseConstraint { get; set; }
+
+ /// <summary>
+ /// Prefix used in forming the constraint description
+ /// </summary>
+ protected string DescriptionPrefix { get; set; }
+
+ /// <summary>
+ /// Construct given a base constraint
+ /// </summary>
+ /// <param name="baseConstraint"></param>
+ protected PrefixConstraint(IResolveConstraint baseConstraint)
+ : base(baseConstraint)
+ {
+ Guard.ArgumentNotNull(baseConstraint, "baseConstraint");
+
+ BaseConstraint = baseConstraint.Resolve();
+ }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get
+ {
+ return string.Format(
+ BaseConstraint is EqualConstraint ? "{0} equal to {1}" : "{0} {1}",
+ DescriptionPrefix,
+ BaseConstraint.Description);
+ }
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// PropertyConstraint extracts a named property and uses
+ /// its value as the actual value for a chained constraint.
+ /// </summary>
+ public class PropertyConstraint : PrefixConstraint
+ {
+ private readonly string name;
+ private object propValue;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PropertyConstraint"/> class.
+ /// </summary>
+ /// <param name="name">The name.</param>
+ /// <param name="baseConstraint">The constraint to apply to the property.</param>
+ public PropertyConstraint(string name, IConstraint baseConstraint)
+ : base(baseConstraint)
+ {
+ this.name = name;
+ this.DescriptionPrefix = "property " + name;
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ // TODO: Use an error result for null
+ Guard.ArgumentNotNull(actual, "actual");
+
+ Type actualType = actual as Type;
+ if (actualType == null)
+ actualType = actual.GetType();
+
+ PropertyInfo property = actualType.GetProperty(name,
+ BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
+
+ // TODO: Use an error result here
+ if (property == null)
+ throw new ArgumentException(string.Format("Property {0} was not found", name), "name");
+
+ propValue = property.GetValue(actual, null);
+ return new ConstraintResult(this, propValue, BaseConstraint.ApplyTo(propValue).IsSuccess);
+ }
+
+ /// <summary>
+ /// Returns the string representation of the constraint.
+ /// </summary>
+ /// <returns></returns>
+ protected override string GetStringRepresentation()
+ {
+ return string.Format("<property {0} {1}>", name, BaseConstraint);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// PropertyExistsConstraint tests that a named property
+ /// exists on the object provided through Match.
+ ///
+ /// Originally, PropertyConstraint provided this feature
+ /// in addition to making optional tests on the value
+ /// of the property. The two constraints are now separate.
+ /// </summary>
+ public class PropertyExistsConstraint : Constraint
+ {
+ private readonly string name;
+
+ Type actualType;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PropertyExistsConstraint"/> class.
+ /// </summary>
+ /// <param name="name">The name of the property.</param>
+ public PropertyExistsConstraint(string name)
+ : base(name)
+ {
+ this.name = name;
+ }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "property " + name; }
+ }
+
+ /// <summary>
+ /// Test whether the property exists for a given object
+ /// </summary>
+ /// <param name="actual">The object to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ Guard.ArgumentNotNull(actual, "actual");
+
+ actualType = actual as Type;
+ if (actualType == null)
+ actualType = actual.GetType();
+
+ PropertyInfo property = actualType.GetProperty(name,
+ BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
+ return new ConstraintResult(this, actualType, property != null);
+ }
+
+ /// <summary>
+ /// Returns the string representation of the constraint.
+ /// </summary>
+ /// <returns></returns>
+ protected override string GetStringRepresentation()
+ {
+ return string.Format("<propertyexists {0}>", name);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// RangeConstraint tests whether two _values are within a
+ /// specified range.
+ /// </summary>
+ public class RangeConstraint : Constraint
+ {
+ private readonly IComparable from;
+ private readonly IComparable to;
+
+ private ComparisonAdapter comparer = ComparisonAdapter.Default;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RangeConstraint"/> class.
+ /// </summary>
+ /// <remarks>from must be less than or equal to true</remarks>
+ /// <param name="from">Inclusive beginning of the range. Must be less than or equal to to.</param>
+ /// <param name="to">Inclusive end of the range. Must be greater than or equal to from.</param>
+ public RangeConstraint(IComparable from, IComparable to) : base( from, to )
+ {
+ // Issue #21 - https://github.com/nunit/nunit-framework/issues/21
+ // from must be less than or equal to to
+ if (comparer.Compare(from, to) > 0)
+ throw new ArgumentException( "from must be less than to" );
+
+ this.from = from;
+ this.to = to;
+ }
+
+ /// <summary>
+ /// Gets text describing a constraint
+ /// </summary>
+ public override string Description
+ {
+ get { return string.Format("in range ({0},{1})", from, to); }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ if ( from == null || to == null || actual == null)
+ throw new ArgumentException( "Cannot compare using a null reference", "actual" );
+
+ bool isInsideRange = comparer.Compare(from, actual) <= 0 && comparer.Compare(to, actual) >= 0;
+ return new ConstraintResult(this, actual, isInsideRange);
+ }
+
+ /// <summary>
+ /// Modifies the constraint to use an <see cref="IComparer"/> and returns self.
+ /// </summary>
+ public RangeConstraint Using(IComparer comparer)
+ {
+ this.comparer = ComparisonAdapter.For(comparer);
+ return this;
+ }
+
+ /// <summary>
+ /// Modifies the constraint to use an <see cref="IComparer{T}"/> and returns self.
+ /// </summary>
+ public RangeConstraint Using<T>(IComparer<T> comparer)
+ {
+ this.comparer = ComparisonAdapter.For(comparer);
+ return this;
+ }
+
+ /// <summary>
+ /// Modifies the constraint to use a <see cref="Comparison{T}"/> and returns self.
+ /// </summary>
+ public RangeConstraint Using<T>(Comparison<T> comparer)
+ {
+ this.comparer = ComparisonAdapter.For(comparer);
+ return this;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Text.RegularExpressions;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// RegexConstraint can test whether a string matches
+ /// the pattern provided.
+ /// </summary>
+ public class RegexConstraint : StringConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RegexConstraint"/> class.
+ /// </summary>
+ /// <param name="pattern">The pattern.</param>
+ public RegexConstraint(string pattern) : base(pattern)
+ {
+ descriptionText = "String matching";
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ protected override bool Matches(string actual)
+ {
+ return actual != null && Regex.IsMatch(
+ actual,
+ this.expected,
+ this.caseInsensitive ? RegexOptions.IgnoreCase : RegexOptions.None);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// ResolvableConstraintExpression is used to represent a compound
+ /// constraint being constructed at a point where the last operator
+ /// may either terminate the expression or may have additional
+ /// qualifying constraints added to it.
+ ///
+ /// It is used, for example, for a Property element or for
+ /// an Exception element, either of which may be optionally
+ /// followed by constraints that apply to the property or
+ /// exception.
+ /// </summary>
+ public class ResolvableConstraintExpression : ConstraintExpression, IResolveConstraint
+ {
+ /// <summary>
+ /// Create a new instance of ResolvableConstraintExpression
+ /// </summary>
+ public ResolvableConstraintExpression() { }
+
+ /// <summary>
+ /// Create a new instance of ResolvableConstraintExpression,
+ /// passing in a pre-populated ConstraintBuilder.
+ /// </summary>
+ public ResolvableConstraintExpression(ConstraintBuilder builder)
+ : base(builder) { }
+
+ /// <summary>
+ /// Appends an And Operator to the expression
+ /// </summary>
+ public ConstraintExpression And
+ {
+ get { return this.Append(new AndOperator()); }
+ }
+
+ /// <summary>
+ /// Appends an Or operator to the expression.
+ /// </summary>
+ public ConstraintExpression Or
+ {
+ get { return this.Append(new OrOperator()); }
+ }
+
+ #region IResolveConstraint Members
+
+ /// <summary>
+ /// Resolve the current expression to a Constraint
+ /// </summary>
+ IConstraint IResolveConstraint.Resolve()
+ {
+ return builder.Resolve();
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// ReusableConstraint wraps a constraint expression after
+ /// resolving it so that it can be reused consistently.
+ /// </summary>
+ public class ReusableConstraint : IResolveConstraint
+ {
+ private readonly IConstraint constraint;
+
+ /// <summary>
+ /// Construct a ReusableConstraint from a constraint expression
+ /// </summary>
+ /// <param name="c">The expression to be resolved and reused</param>
+ public ReusableConstraint(IResolveConstraint c)
+ {
+ this.constraint = c.Resolve();
+ }
+
+ /// <summary>
+ /// Converts a constraint to a ReusableConstraint
+ /// </summary>
+ /// <param name="c">The constraint to be converted</param>
+ /// <returns>A ReusableConstraint</returns>
+ public static implicit operator ReusableConstraint(Constraint c)
+ {
+ return new ReusableConstraint(c);
+ }
+
+ /// <summary>
+ /// Returns a <see cref="System.String"/> that represents this instance.
+ /// </summary>
+ /// <returns>
+ /// A <see cref="System.String"/> that represents this instance.
+ /// </returns>
+ public override string ToString()
+ {
+ return constraint.ToString();
+ }
+
+ #region IResolveConstraint Members
+
+ /// <summary>
+ /// Return the top-level constraint for this expression
+ /// </summary>
+ /// <returns></returns>
+ public IConstraint Resolve()
+ {
+ return constraint;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// SameAsConstraint tests whether an object is identical to
+ /// the object passed to its constructor
+ /// </summary>
+ public class SameAsConstraint : Constraint
+ {
+ private readonly object expected;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SameAsConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The expected object.</param>
+ public SameAsConstraint(object expected) : base(expected)
+ {
+ this.expected = expected;
+ }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "same as " + MsgUtils.FormatValue(expected); }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ bool hasSucceeded = ReferenceEquals(expected, actual);
+
+ return new ConstraintResult(this, actual, hasSucceeded);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !PORTABLE
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Summary description for SamePathConstraint.
+ /// </summary>
+ public class SamePathConstraint : PathConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SamePathConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The expected path</param>
+ public SamePathConstraint(string expected) : base(expected) { }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "Path matching " + MsgUtils.FormatValue(expected); }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ protected override bool Matches(string actual)
+ {
+ return actual != null && StringUtil.StringsEqual(Canonicalize(expected), Canonicalize(actual), caseInsensitive);
+ }
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !PORTABLE
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// SamePathOrUnderConstraint tests that one path is under another
+ /// </summary>
+ public class SamePathOrUnderConstraint : PathConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SamePathOrUnderConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The expected path</param>
+ public SamePathOrUnderConstraint(string expected) : base(expected) { }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "Path under or matching " + MsgUtils.FormatValue(expected); }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ protected override bool Matches(string actual)
+ {
+ if (actual == null) return false;
+
+ string path1 = Canonicalize(expected);
+ string path2 = Canonicalize(actual);
+ return StringUtil.StringsEqual(path1, path2, caseInsensitive) || IsSubPath(path1, path2);
+ }
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// SomeItemsConstraint applies another constraint to each
+ /// item in a collection, succeeding if any of them succeeds.
+ /// </summary>
+ public class SomeItemsConstraint : PrefixConstraint
+ {
+ /// <summary>
+ /// Construct a SomeItemsConstraint on top of an existing constraint
+ /// </summary>
+ /// <param name="itemConstraint"></param>
+ public SomeItemsConstraint(IConstraint itemConstraint)
+ : base(itemConstraint)
+ {
+ DescriptionPrefix = "some item";
+ }
+
+ /// <summary>
+ /// The display name of this Constraint for use by ToString().
+ /// The default value is the name of the constraint with
+ /// trailing "Constraint" removed. Derived classes may set
+ /// this to another name in their constructors.
+ /// </summary>
+ public override string DisplayName { get { return "Some"; } }
+
+ /// <summary>
+ /// Apply the item constraint to each item in the collection,
+ /// succeeding if any item succeeds.
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ if (!(actual is IEnumerable))
+ throw new ArgumentException("The actual value must be an IEnumerable", "actual");
+
+ foreach (object item in (IEnumerable)actual)
+ if (BaseConstraint.ApplyTo(item).IsSuccess)
+ return new ConstraintResult(this, actual, ConstraintStatus.Success);
+
+ return new ConstraintResult(this, actual, ConstraintStatus.Failure);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// StartsWithConstraint can test whether a string starts
+ /// with an expected substring.
+ /// </summary>
+ public class StartsWithConstraint : StringConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StartsWithConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The expected string</param>
+ public StartsWithConstraint(string expected) : base(expected)
+ {
+ descriptionText = "String starting with";
+ }
+
+ /// <summary>
+ /// Test whether the constraint is matched by the actual value.
+ /// This is a template method, which calls the IsMatch method
+ /// of the derived class.
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ protected override bool Matches(string actual)
+ {
+ if (this.caseInsensitive)
+ return actual != null && actual.ToLower().StartsWith(expected.ToLower());
+ else
+ return actual != null && actual.StartsWith(expected);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// StringConstraint is the abstract base for constraints
+ /// that operate on strings. It supports the IgnoreCase
+ /// modifier for string operations.
+ /// </summary>
+ public abstract class StringConstraint : Constraint
+ {
+ /// <summary>
+ /// The expected value
+ /// </summary>
+ protected string expected;
+
+ /// <summary>
+ /// Indicates whether tests should be case-insensitive
+ /// </summary>
+ protected bool caseInsensitive;
+
+ /// <summary>
+ /// Description of this constraint
+ /// </summary>
+ protected string descriptionText;
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get
+ {
+ string desc = string.Format("{0} {1}", descriptionText, MsgUtils.FormatValue(expected));
+ if (caseInsensitive)
+ desc += ", ignoring case";
+ return desc;
+ }
+ }
+
+ /// <summary>
+ /// Constructs a StringConstraint without an expected value
+ /// </summary>
+ protected StringConstraint() { }
+
+ /// <summary>
+ /// Constructs a StringConstraint given an expected value
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ protected StringConstraint(string expected)
+ : base(expected)
+ {
+ this.expected = expected;
+ }
+
+ /// <summary>
+ /// Modify the constraint to ignore case in matching.
+ /// </summary>
+ public StringConstraint IgnoreCase
+ {
+ get { caseInsensitive = true; return this; }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ string actualAsString = actual as string;
+ if (actual != null && actualAsString == null)
+ throw new ArgumentException("Actual value must be a string", "actual");
+
+ return new ConstraintResult(this, actual, Matches(actualAsString));
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given string
+ /// </summary>
+ /// <param name="actual">The string to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ protected abstract bool Matches(string actual);
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !PORTABLE
+using System;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// SubPathConstraint tests that the actual path is under the expected path
+ /// </summary>
+ public class SubPathConstraint : PathConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SubPathConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The expected path</param>
+ public SubPathConstraint(string expected) : base(expected) { }
+
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "Subpath of " + MsgUtils.FormatValue(expected); }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ protected override bool Matches(string actual)
+ {
+ return actual != null & IsSubPath(Canonicalize(expected), Canonicalize(actual));
+ }
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// SubstringConstraint can test whether a string contains
+ /// the expected substring.
+ /// </summary>
+ public class SubstringConstraint : StringConstraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SubstringConstraint"/> class.
+ /// </summary>
+ /// <param name="expected">The expected.</param>
+ public SubstringConstraint(string expected) : base(expected)
+ {
+ descriptionText = "String containing";
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ protected override bool Matches(string actual)
+ {
+ if (this.caseInsensitive)
+ return actual != null && actual.ToLower().IndexOf(expected.ToLower()) >= 0;
+ else
+ return actual != null && actual.IndexOf(expected) >= 0;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// ThrowsConstraint is used to test the exception thrown by
+ /// a delegate by applying a constraint to it.
+ /// </summary>
+ public class ThrowsConstraint : PrefixConstraint
+ {
+ private Exception caughtException;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ThrowsConstraint"/> class,
+ /// using a constraint to be applied to the exception.
+ /// </summary>
+ /// <param name="baseConstraint">A constraint to apply to the caught exception.</param>
+ public ThrowsConstraint(IConstraint baseConstraint)
+ : base(baseConstraint) { }
+
+ /// <summary>
+ /// Get the actual exception thrown - used by Assert.Throws.
+ /// </summary>
+ public Exception ActualException
+ {
+ get { return caughtException; }
+ }
+
+ #region Constraint Overrides
+
+ /// <summary>
+ /// Gets text describing a constraint
+ /// </summary>
+ public override string Description
+ {
+ get { return BaseConstraint.Description; }
+ }
+
+ /// <summary>
+ /// Executes the code of the delegate and captures any exception.
+ /// If a non-null base constraint was provided, it applies that
+ /// constraint to the exception.
+ /// </summary>
+ /// <param name="actual">A delegate representing the code to be tested</param>
+ /// <returns>True if an exception is thrown and the constraint succeeds, otherwise false</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ //TestDelegate code = actual as TestDelegate;
+ //if (code == null)
+ // throw new ArgumentException(
+ // string.Format("The actual value must be a TestDelegate but was {0}", actual.GetType().Name), "actual");
+
+ //caughtException = null;
+
+ //try
+ //{
+ // code();
+ //}
+ //catch (Exception ex)
+ //{
+ // caughtException = ex;
+ //}
+
+ caughtException = ExceptionInterceptor.Intercept(actual);
+
+ return new ThrowsConstraintResult(
+ this,
+ caughtException,
+ caughtException != null
+ ? BaseConstraint.ApplyTo(caughtException)
+ : null);
+ }
+
+ /// <summary>
+ /// Converts an ActualValueDelegate to a TestDelegate
+ /// before calling the primary overload.
+ /// </summary>
+ /// <param name="del"></param>
+ /// <returns></returns>
+ public override ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del)
+ {
+ //TestDelegate testDelegate = new TestDelegate(delegate { del(); });
+ //return ApplyTo((object)testDelegate);
+ return ApplyTo(new GenericInvocationDescriptor<TActual>(del));
+ }
+
+ #endregion
+
+ #region Nested Result Class
+
+ private class ThrowsConstraintResult : ConstraintResult
+ {
+ private readonly ConstraintResult baseResult;
+
+ public ThrowsConstraintResult(ThrowsConstraint constraint,
+ Exception caughtException,
+ ConstraintResult baseResult)
+ : base(constraint, caughtException)
+ {
+ if (caughtException != null && baseResult.IsSuccess)
+ Status = ConstraintStatus.Success;
+ else
+ Status = ConstraintStatus.Failure;
+
+ this.baseResult = baseResult;
+ }
+
+ /// <summary>
+ /// Write the actual value for a failing constraint test to a
+ /// MessageWriter. This override only handles the special message
+ /// used when an exception is expected but none is thrown.
+ /// </summary>
+ /// <param name="writer">The writer on which the actual value is displayed</param>
+ public override void WriteActualValueTo(MessageWriter writer)
+ {
+ if (ActualValue == null)
+ writer.Write("no exception thrown");
+ else
+ baseResult.WriteActualValueTo(writer);
+ }
+ }
+
+ #endregion
+
+ #region ExceptionInterceptor
+
+ internal class ExceptionInterceptor
+ {
+ private ExceptionInterceptor() { }
+
+ internal static Exception Intercept(object invocation)
+ {
+ var invocationDescriptor = GetInvocationDescriptor(invocation);
+
+#if NET_4_0 || NET_4_5 || PORTABLE
+ if (AsyncInvocationRegion.IsAsyncOperation(invocationDescriptor.Delegate))
+ {
+ using (var region = AsyncInvocationRegion.Create(invocationDescriptor.Delegate))
+ {
+ try
+ {
+ object result = invocationDescriptor.Invoke();
+ region.WaitForPendingOperationsToComplete(result);
+ return null;
+ }
+ catch (Exception ex)
+ {
+ return ex;
+ }
+ }
+ }
+ else
+#endif
+ {
+ try
+ {
+ invocationDescriptor.Invoke();
+ return null;
+ }
+ catch (Exception ex)
+ {
+ return ex;
+ }
+ }
+ }
+
+ private static IInvocationDescriptor GetInvocationDescriptor(object actual)
+ {
+ var invocationDescriptor = actual as IInvocationDescriptor;
+
+ if (invocationDescriptor == null)
+ {
+ var testDelegate = actual as TestDelegate;
+
+ if (testDelegate != null)
+ {
+ invocationDescriptor = new VoidInvocationDescriptor(testDelegate);
+ }
+
+#if NET_4_0 || NET_4_5 || PORTABLE
+ else
+ {
+ var asyncTestDelegate = actual as AsyncTestDelegate;
+ if (asyncTestDelegate != null)
+ {
+ invocationDescriptor = new GenericInvocationDescriptor<System.Threading.Tasks.Task>(() => asyncTestDelegate());
+ }
+ }
+#endif
+ }
+ if (invocationDescriptor == null)
+ throw new ArgumentException(
+ String.Format(
+ "The actual value must be a TestDelegate or AsyncTestDelegate but was {0}",
+ actual.GetType().Name),
+ "actual");
+
+ return invocationDescriptor;
+ }
+ }
+
+#endregion
+
+#region InvocationDescriptor
+
+ internal class GenericInvocationDescriptor<T> : IInvocationDescriptor
+ {
+ private readonly ActualValueDelegate<T> _del;
+
+ public GenericInvocationDescriptor(ActualValueDelegate<T> del)
+ {
+ _del = del;
+ }
+
+ public object Invoke()
+ {
+ return _del();
+ }
+
+ public Delegate Delegate
+ {
+ get { return _del; }
+ }
+ }
+
+ private interface IInvocationDescriptor
+ {
+ Delegate Delegate { get; }
+ object Invoke();
+ }
+
+ private class VoidInvocationDescriptor : IInvocationDescriptor
+ {
+ private readonly TestDelegate _del;
+
+ public VoidInvocationDescriptor(TestDelegate del)
+ {
+ _del = del;
+ }
+
+ public object Invoke()
+ {
+ _del();
+ return null;
+ }
+
+ public Delegate Delegate
+ {
+ get { return _del; }
+ }
+ }
+
+#endregion
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// ThrowsExceptionConstraint tests that an exception has
+ /// been thrown, without any further tests.
+ /// </summary>
+ public class ThrowsExceptionConstraint : Constraint
+ {
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "an exception to be thrown"; }
+ }
+
+ /// <summary>
+ /// Executes the code and returns success if an exception is thrown.
+ /// </summary>
+ /// <param name="actual">A delegate representing the code to be tested</param>
+ /// <returns>True if an exception is thrown, otherwise false</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ TestDelegate code = actual as TestDelegate;
+ Exception caughtException = null;
+
+ if (code != null)
+ {
+ try
+ {
+ code();
+ }
+ catch (Exception ex)
+ {
+ caughtException = ex;
+ }
+ }
+#if NET_4_0 || NET_4_5 || PORTABLE
+ AsyncTestDelegate asyncCode = actual as AsyncTestDelegate;
+ if (asyncCode != null)
+ {
+ using (var region = AsyncInvocationRegion.Create(asyncCode))
+ {
+ try
+ {
+ var task = asyncCode();
+ region.WaitForPendingOperationsToComplete(task);
+ }
+ catch (Exception ex)
+ {
+ caughtException = ex;
+ }
+ }
+ }
+ if (code == null && asyncCode == null)
+#else
+ else
+#endif
+ {
+ throw new ArgumentException(string.Format("The actual value must be a TestDelegate or AsyncTestDelegate but was {0}", actual.GetType().Name), "actual");
+ }
+ return new ThrowsExceptionConstraintResult(this, caughtException);
+ }
+
+ /// <summary>
+ /// Returns the ActualValueDelegate itself as the value to be tested.
+ /// </summary>
+ /// <param name="del">A delegate representing the code to be tested</param>
+ /// <returns>The delegate itself</returns>
+ protected override object GetTestObject<TActual>(ActualValueDelegate<TActual> del)
+ {
+ return new TestDelegate(() => del());
+ }
+
+ #region Nested Result Class
+
+ class ThrowsExceptionConstraintResult : ConstraintResult
+ {
+ public ThrowsExceptionConstraintResult(ThrowsExceptionConstraint constraint, Exception caughtException)
+ : base(constraint, caughtException, caughtException != null) { }
+
+ public override void WriteActualValueTo(MessageWriter writer)
+ {
+ if (this.Status == ConstraintStatus.Failure)
+ writer.Write("no exception thrown");
+ else
+ base.WriteActualValueTo(writer);
+ }
+ }
+
+ #endregion
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// ThrowsNothingConstraint tests that a delegate does not
+ /// throw an exception.
+ /// </summary>
+ public class ThrowsNothingConstraint : Constraint
+ {
+ // TODO: This constraint needs tests
+ private Exception caughtException;
+
+ /// <summary>
+ /// Gets text describing a constraint
+ /// </summary>
+ public override string Description
+ {
+ get { return "No Exception to be thrown"; }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True if no exception is thrown, otherwise false</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ caughtException = ThrowsConstraint.ExceptionInterceptor.Intercept(actual);
+ return new ConstraintResult(this, caughtException, caughtException == null);
+ }
+
+ /// <summary>
+ /// Applies the constraint to an ActualValueDelegate that returns
+ /// the value to be tested. The default implementation simply evaluates
+ /// the delegate but derived classes may override it to provide for
+ /// delayed processing.
+ /// </summary>
+ /// <param name="del">An ActualValueDelegate</param>
+ /// <returns>A ConstraintResult</returns>
+ public override ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del)
+ {
+ return ApplyTo(new ThrowsConstraint.GenericInvocationDescriptor<TActual>(del));
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// The Tolerance class generalizes the notion of a tolerance
+ /// within which an equality test succeeds. Normally, it is
+ /// used with numeric types, but it can be used with any
+ /// type that supports taking a difference between two
+ /// objects and comparing that difference to a value.
+ /// </summary>
+ public class Tolerance
+ {
+ private readonly ToleranceMode mode;
+ private readonly object amount;
+
+ private const string ModeMustFollowTolerance = "Tolerance amount must be specified before setting mode";
+ private const string MultipleToleranceModes = "Tried to use multiple tolerance modes at the same time";
+ private const string NumericToleranceRequired = "A numeric tolerance is required";
+
+ /// <summary>
+ /// Returns a default Tolerance object, equivalent to
+ /// specifying an exact match unless <see cref="GlobalSettings.DefaultFloatingPointTolerance"/>
+ /// is set, in which case, the <see cref="GlobalSettings.DefaultFloatingPointTolerance"/>
+ /// will be used.
+ /// </summary>
+ public static Tolerance Default
+ {
+ get { return new Tolerance(0, ToleranceMode.Unset); }
+ }
+
+ /// <summary>
+ /// Returns an empty Tolerance object, equivalent to
+ /// specifying an exact match even if
+ /// <see cref="GlobalSettings.DefaultFloatingPointTolerance"/> is set.
+ /// </summary>
+ public static Tolerance Exact
+ {
+ get { return new Tolerance(0, ToleranceMode.Linear); }
+ }
+
+ /// <summary>
+ /// Constructs a linear tolerance of a specified amount
+ /// </summary>
+ public Tolerance(object amount) : this(amount, ToleranceMode.Linear) { }
+
+ /// <summary>
+ /// Constructs a tolerance given an amount and <see cref="ToleranceMode"/>
+ /// </summary>
+ private Tolerance(object amount, ToleranceMode mode)
+ {
+ this.amount = amount;
+ this.mode = mode;
+ }
+
+ /// <summary>
+ /// Gets the <see cref="ToleranceMode"/> for the current Tolerance
+ /// </summary>
+ public ToleranceMode Mode
+ {
+ get { return this.mode; }
+ }
+
+
+ /// <summary>
+ /// Tests that the current Tolerance is linear with a
+ /// numeric value, throwing an exception if it is not.
+ /// </summary>
+ private void CheckLinearAndNumeric()
+ {
+ if (mode != ToleranceMode.Linear)
+ throw new InvalidOperationException(mode == ToleranceMode.Unset
+ ? ModeMustFollowTolerance
+ : MultipleToleranceModes);
+
+ if (!Numerics.IsNumericType(amount))
+ throw new InvalidOperationException(NumericToleranceRequired);
+ }
+
+ /// <summary>
+ /// Gets the value of the current Tolerance instance.
+ /// </summary>
+ public object Value
+ {
+ get { return amount; }
+ }
+
+ /// <summary>
+ /// Returns a new tolerance, using the current amount as a percentage.
+ /// </summary>
+ public Tolerance Percent
+ {
+ get
+ {
+ CheckLinearAndNumeric();
+ return new Tolerance(this.amount, ToleranceMode.Percent);
+ }
+ }
+
+ /// <summary>
+ /// Returns a new tolerance, using the current amount in Ulps
+ /// </summary>
+ public Tolerance Ulps
+ {
+ get
+ {
+ CheckLinearAndNumeric();
+ return new Tolerance(this.amount, ToleranceMode.Ulps);
+ }
+ }
+
+ /// <summary>
+ /// Returns a new tolerance with a <see cref="TimeSpan"/> as the amount, using
+ /// the current amount as a number of days.
+ /// </summary>
+ public Tolerance Days
+ {
+ get
+ {
+ CheckLinearAndNumeric();
+ return new Tolerance(TimeSpan.FromDays(Convert.ToDouble(amount)));
+ }
+ }
+
+ /// <summary>
+ /// Returns a new tolerance with a <see cref="TimeSpan"/> as the amount, using
+ /// the current amount as a number of hours.
+ /// </summary>
+ public Tolerance Hours
+ {
+ get
+ {
+ CheckLinearAndNumeric();
+ return new Tolerance(TimeSpan.FromHours(Convert.ToDouble(amount)));
+ }
+ }
+
+ /// <summary>
+ /// Returns a new tolerance with a <see cref="TimeSpan"/> as the amount, using
+ /// the current amount as a number of minutes.
+ /// </summary>
+ public Tolerance Minutes
+ {
+ get
+ {
+ CheckLinearAndNumeric();
+ return new Tolerance(TimeSpan.FromMinutes(Convert.ToDouble(amount)));
+ }
+ }
+
+ /// <summary>
+ /// Returns a new tolerance with a <see cref="TimeSpan"/> as the amount, using
+ /// the current amount as a number of seconds.
+ /// </summary>
+ public Tolerance Seconds
+ {
+ get
+ {
+ CheckLinearAndNumeric();
+ return new Tolerance(TimeSpan.FromSeconds(Convert.ToDouble(amount)));
+ }
+ }
+
+ /// <summary>
+ /// Returns a new tolerance with a <see cref="TimeSpan"/> as the amount, using
+ /// the current amount as a number of milliseconds.
+ /// </summary>
+ public Tolerance Milliseconds
+ {
+ get
+ {
+ CheckLinearAndNumeric();
+ return new Tolerance(TimeSpan.FromMilliseconds(Convert.ToDouble(amount)));
+ }
+ }
+
+ /// <summary>
+ /// Returns a new tolerance with a <see cref="TimeSpan"/> as the amount, using
+ /// the current amount as a number of clock ticks.
+ /// </summary>
+ public Tolerance Ticks
+ {
+ get
+ {
+ CheckLinearAndNumeric();
+ return new Tolerance(TimeSpan.FromTicks(Convert.ToInt64(amount)));
+ }
+ }
+
+ /// <summary>
+ /// Returns true if the current tolerance has not been set or is using the .
+ /// </summary>
+ public bool IsUnsetOrDefault
+ {
+ get { return mode == ToleranceMode.Unset; }
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// Modes in which the tolerance value for a comparison can be interpreted.
+ /// </summary>
+ public enum ToleranceMode
+ {
+ /// <summary>
+ /// The tolerance was created with a value, without specifying
+ /// how the value would be used. This is used to prevent setting
+ /// the mode more than once and is generally changed to Linear
+ /// upon execution of the test.
+ /// </summary>
+ Unset,
+ /// <summary>
+ /// The tolerance is used as a numeric range within which
+ /// two compared _values are considered to be equal.
+ /// </summary>
+ Linear,
+ /// <summary>
+ /// Interprets the tolerance as the percentage by which
+ /// the two compared _values my deviate from each other.
+ /// </summary>
+ Percent,
+ /// <summary>
+ /// Compares two _values based in their distance in
+ /// representable numbers.
+ /// </summary>
+ Ulps
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// TrueConstraint tests that the actual value is true
+ /// </summary>
+ public class TrueConstraint : Constraint
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TrueConstraint"/> class.
+ /// </summary>
+ public TrueConstraint()
+ {
+ Description = "True";
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ return new ConstraintResult(this, actual, true.Equals(actual));
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// TypeConstraint is the abstract base for constraints
+ /// that take a Type as their expected value.
+ /// </summary>
+ public abstract class TypeConstraint : Constraint
+ {
+ /// <summary>
+ /// The expected Type used by the constraint
+ /// </summary>
+ protected Type expectedType;
+
+ /// <summary>
+ /// The type of the actual argument to which the constraint was applied
+ /// </summary>
+ protected Type actualType;
+
+ /// <summary>
+ /// Construct a TypeConstraint for a given Type
+ /// </summary>
+ /// <param name="type">The expected type for the constraint</param>
+ /// <param name="descriptionPrefix">Prefix used in forming the constraint description</param>
+ protected TypeConstraint(Type type, string descriptionPrefix)
+ : base(type)
+ {
+ this.expectedType = type;
+ this.Description = descriptionPrefix + MsgUtils.FormatValue(expectedType);
+ }
+
+ /// <summary>
+ /// Applies the constraint to an actual value, returning a ConstraintResult.
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>A ConstraintResult</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ actualType = actual == null ? null : actual.GetType();
+ return new ConstraintResult(this, actualType, this.Matches(actual));
+ }
+
+ /// <summary>
+ /// Apply the constraint to an actual value, returning true if it succeeds
+ /// </summary>
+ /// <param name="actual">The actual argument</param>
+ /// <returns>True if the constraint succeeds, otherwise false.</returns>
+ protected abstract bool Matches(object actual);
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections;
+using System.Collections.Generic;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// UniqueItemsConstraint tests whether all the items in a
+ /// collection are unique.
+ /// </summary>
+ public class UniqueItemsConstraint : CollectionItemsEqualConstraint
+ {
+ /// <summary>
+ /// The Description of what this constraint tests, for
+ /// use in messages and in the ConstraintResult.
+ /// </summary>
+ public override string Description
+ {
+ get { return "all items unique"; }
+ }
+
+ /// <summary>
+ /// Check that all items are unique.
+ /// </summary>
+ /// <param name="actual"></param>
+ /// <returns></returns>
+ protected override bool Matches(IEnumerable actual)
+ {
+ var list = new List<object>();
+
+ foreach (object o1 in actual)
+ {
+ foreach (object o2 in list)
+ if (ItemsEqual(o1, o2))
+ return false;
+ list.Add(o1);
+ }
+
+ return true;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !SILVERLIGHT && !PORTABLE
+using System;
+using System.IO;
+using System.Xml.Serialization;
+
+namespace NUnit.Framework.Constraints
+{
+ /// <summary>
+ /// XmlSerializableConstraint tests whether
+ /// an object is serializable in xml format.
+ /// </summary>
+ public class XmlSerializableConstraint : Constraint
+ {
+ private XmlSerializer serializer;
+
+ /// <summary>
+ /// Gets text describing a constraint
+ /// </summary>
+ public override string Description
+ {
+ get { return "xml serializable"; }
+ }
+
+ /// <summary>
+ /// Test whether the constraint is satisfied by a given value
+ /// </summary>
+ /// <param name="actual">The value to be tested</param>
+ /// <returns>True for success, false for failure</returns>
+ public override ConstraintResult ApplyTo<TActual>(TActual actual)
+ {
+ if(actual == null)
+ throw new ArgumentNullException("actual");
+
+ MemoryStream stream = new MemoryStream();
+
+ bool succeeded = false;
+
+ try
+ {
+ serializer = new XmlSerializer(actual.GetType());
+
+ serializer.Serialize(stream, actual);
+
+ stream.Seek(0, SeekOrigin.Begin);
+
+ succeeded = serializer.Deserialize(stream) != null;
+ }
+ catch (NotSupportedException)
+ {
+ // Ignore and return failure
+ }
+ catch (InvalidOperationException)
+ {
+ // Ignore and return failure
+ }
+
+ return new ConstraintResult(this, actual.GetType(), succeeded);
+ }
+
+ /// <summary>
+ /// Returns the string representation of this constraint
+ /// </summary>
+ protected override string GetStringRepresentation()
+ {
+ return "<xmlserializable>";
+ }
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+
+using NUnit.Framework.Constraints;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Helper class with properties and methods that supply
+ /// a number of constraints used in Asserts.
+ /// </summary>
+ public static class Does
+ {
+ #region Not
+
+ /// <summary>
+ /// Returns a ConstraintExpression that negates any
+ /// following constraint.
+ /// </summary>
+ public static ConstraintExpression Not
+ {
+ get { return new ConstraintExpression().Not; }
+ }
+
+ #endregion
+
+ #region Exist
+
+#if !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Returns a constraint that succeeds if the value
+ /// is a file or directory and it exists.
+ /// </summary>
+ public static FileOrDirectoryExistsConstraint Exist
+ {
+ get { return new FileOrDirectoryExistsConstraint(); }
+ }
+#endif
+
+ #endregion
+
+ #region Contain
+
+ /// <summary>
+ /// Returns a new CollectionContainsConstraint checking for the
+ /// presence of a particular object in the collection.
+ /// </summary>
+ public static CollectionContainsConstraint Contain(object expected)
+ {
+ return new CollectionContainsConstraint(expected);
+ }
+
+ /// <summary>
+ /// Returns a new ContainsConstraint. This constraint
+ /// will, in turn, make use of the appropriate second-level
+ /// constraint, depending on the type of the actual argument.
+ /// This overload is only used if the item sought is a string,
+ /// since any other type implies that we are looking for a
+ /// collection member.
+ /// </summary>
+ public static ContainsConstraint Contain(string expected)
+ {
+ return new ContainsConstraint(expected);
+ }
+
+ #endregion
+
+ #region StartWith
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value starts with the substring supplied as an argument.
+ /// </summary>
+ public static StartsWithConstraint StartWith(string expected)
+ {
+ return new StartsWithConstraint(expected);
+ }
+
+ #endregion
+
+ #region EndWith
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value ends with the substring supplied as an argument.
+ /// </summary>
+ public static EndsWithConstraint EndWith(string expected)
+ {
+ return new EndsWithConstraint(expected);
+ }
+
+ #endregion
+
+ #region Match
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value matches the regular expression supplied as an argument.
+ /// </summary>
+ public static RegexConstraint Match(string pattern)
+ {
+ return new RegexConstraint(pattern);
+ }
+
+ #endregion
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ using Interfaces;
+
+ /// <summary>
+ /// Thrown when an assertion failed.
+ /// </summary>
+ //[Serializable]
+ public class AssertionException : ResultStateException
+ {
+ /// <param name="message">The error message that explains
+ /// the reason for the exception</param>
+ public AssertionException (string message) : base(message)
+ {}
+
+ /// <param name="message">The error message that explains
+ /// the reason for the exception</param>
+ /// <param name="inner">The exception that caused the
+ /// current exception</param>
+ public AssertionException(string message, Exception inner) :
+ base(message, inner)
+ {}
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Serialization Constructor
+ /// </summary>
+ protected AssertionException(System.Runtime.Serialization.SerializationInfo info,
+ System.Runtime.Serialization.StreamingContext context) : base(info,context)
+ {}
+#endif
+
+ /// <summary>
+ /// Gets the ResultState provided by this exception
+ /// </summary>
+ public override ResultState ResultState
+ {
+ get { return ResultState.Failure; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ using Interfaces;
+
+ /// <summary>
+ /// Thrown when an assertion failed.
+ /// </summary>
+ //[Serializable]
+ public class IgnoreException : ResultStateException
+ {
+ /// <param name="message"></param>
+ public IgnoreException (string message) : base(message)
+ {}
+
+ /// <param name="message">The error message that explains
+ /// the reason for the exception</param>
+ /// <param name="inner">The exception that caused the
+ /// current exception</param>
+ public IgnoreException(string message, Exception inner) :
+ base(message, inner)
+ {}
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Serialization Constructor
+ /// </summary>
+ protected IgnoreException(System.Runtime.Serialization.SerializationInfo info,
+ System.Runtime.Serialization.StreamingContext context) : base(info,context)
+ {}
+#endif
+
+ /// <summary>
+ /// Gets the ResultState provided by this exception
+ /// </summary>
+ public override ResultState ResultState
+ {
+ get { return ResultState.Ignored; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ using Interfaces;
+
+ /// <summary>
+ /// Thrown when a test executes inconclusively.
+ /// </summary>
+ //[Serializable]
+ public class InconclusiveException : ResultStateException
+ {
+ /// <param name="message">The error message that explains
+ /// the reason for the exception</param>
+ public InconclusiveException(string message)
+ : base(message)
+ { }
+
+ /// <param name="message">The error message that explains
+ /// the reason for the exception</param>
+ /// <param name="inner">The exception that caused the
+ /// current exception</param>
+ public InconclusiveException(string message, Exception inner)
+ :
+ base(message, inner)
+ { }
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Serialization Constructor
+ /// </summary>
+ protected InconclusiveException(System.Runtime.Serialization.SerializationInfo info,
+ System.Runtime.Serialization.StreamingContext context)
+ : base(info, context)
+ { }
+#endif
+
+ /// <summary>
+ /// Gets the ResultState provided by this exception
+ /// </summary>
+ public override ResultState ResultState
+ {
+ get { return ResultState.Inconclusive; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ using Interfaces;
+
+ /// <summary>
+ /// Abstract base for Exceptions that terminate a test and provide a ResultState.
+ /// </summary>
+ //[Serializable]
+ public abstract class ResultStateException : Exception
+ {
+ /// <param name="message">The error message that explains
+ /// the reason for the exception</param>
+ public ResultStateException (string message) : base(message)
+ {}
+
+ /// <param name="message">The error message that explains
+ /// the reason for the exception</param>
+ /// <param name="inner">The exception that caused the
+ /// current exception</param>
+ public ResultStateException(string message, Exception inner) :
+ base(message, inner)
+ {}
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Serialization Constructor
+ /// </summary>
+ protected ResultStateException(System.Runtime.Serialization.SerializationInfo info,
+ System.Runtime.Serialization.StreamingContext context) : base(info,context)
+ {}
+#endif
+
+ /// <summary>
+ /// Gets the ResultState provided by this exception
+ /// </summary>
+ public abstract ResultState ResultState { get; }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ using Interfaces;
+
+ /// <summary>
+ /// Thrown when an assertion failed.
+ /// </summary>
+ //[Serializable]
+ public class SuccessException : ResultStateException
+ {
+ /// <param name="message"></param>
+ public SuccessException(string message)
+ : base(message)
+ { }
+
+ /// <param name="message">The error message that explains
+ /// the reason for the exception</param>
+ /// <param name="inner">The exception that caused the
+ /// current exception</param>
+ public SuccessException(string message, Exception inner)
+ :
+ base(message, inner)
+ { }
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Serialization Constructor
+ /// </summary>
+ protected SuccessException(System.Runtime.Serialization.SerializationInfo info,
+ System.Runtime.Serialization.StreamingContext context)
+ : base(info, context)
+ { }
+#endif
+
+ /// <summary>
+ /// Gets the ResultState provided by this exception
+ /// </summary>
+ public override ResultState ResultState
+ {
+ get { return ResultState.Success; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2016 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Constraints;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// GlobalSettings is a place for setting default values used
+ /// by the framework in performing asserts. Anything set through
+ /// this class applies to the entire test run. It should not normally
+ /// be used from within a test, since it is not thread-safe.
+ /// </summary>
+ public static class GlobalSettings
+ {
+ /// <summary>
+ /// Default tolerance for floating point equality
+ /// </summary>
+ public static double DefaultFloatingPointTolerance = 0.0d;
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using NUnit.Framework.Constraints;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Helper class with properties and methods that supply
+ /// a number of constraints used in Asserts.
+ /// </summary>
+ public class Has
+ {
+ #region No
+
+ /// <summary>
+ /// Returns a ConstraintExpression that negates any
+ /// following constraint.
+ /// </summary>
+ public static ConstraintExpression No
+ {
+ get { return new ConstraintExpression().Not; }
+ }
+
+ #endregion
+
+ #region All
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding if all of them succeed.
+ /// </summary>
+ public static ConstraintExpression All
+ {
+ get { return new ConstraintExpression().All; }
+ }
+
+ #endregion
+
+ #region Some
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding if at least one of them succeeds.
+ /// </summary>
+ public static ConstraintExpression Some
+ {
+ get { return new ConstraintExpression().Some; }
+ }
+
+ #endregion
+
+ #region None
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding if all of them fail.
+ /// </summary>
+ public static ConstraintExpression None
+ {
+ get { return new ConstraintExpression().None; }
+ }
+
+ #endregion
+
+ #region Exactly(n)
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding only if a specified number of them succeed.
+ /// </summary>
+ public static ConstraintExpression Exactly(int expectedCount)
+ {
+ return new ConstraintExpression().Exactly(expectedCount);
+ }
+
+ #endregion
+
+ #region Property
+
+ /// <summary>
+ /// Returns a new PropertyConstraintExpression, which will either
+ /// test for the existence of the named property on the object
+ /// being tested or apply any following constraint to that property.
+ /// </summary>
+ public static ResolvableConstraintExpression Property(string name)
+ {
+ return new ConstraintExpression().Property(name);
+ }
+
+ #endregion
+
+ #region Length
+
+ /// <summary>
+ /// Returns a new ConstraintExpression, which will apply the following
+ /// constraint to the Length property of the object being tested.
+ /// </summary>
+ public static ResolvableConstraintExpression Length
+ {
+ get { return Property("Length"); }
+ }
+
+ #endregion
+
+ #region Count
+
+ /// <summary>
+ /// Returns a new ConstraintExpression, which will apply the following
+ /// constraint to the Count property of the object being tested.
+ /// </summary>
+ public static ResolvableConstraintExpression Count
+ {
+ get { return Property("Count"); }
+ }
+
+ #endregion
+
+ #region Message
+
+ /// <summary>
+ /// Returns a new ConstraintExpression, which will apply the following
+ /// constraint to the Message property of the object being tested.
+ /// </summary>
+ public static ResolvableConstraintExpression Message
+ {
+ get { return Property("Message"); }
+ }
+
+ #endregion
+
+ #region InnerException
+
+ /// <summary>
+ /// Returns a new ConstraintExpression, which will apply the following
+ /// constraint to the InnerException property of the object being tested.
+ /// </summary>
+ public static ResolvableConstraintExpression InnerException
+ {
+ get { return Property("InnerException"); }
+ }
+
+ #endregion
+
+ #region Attribute
+
+ /// <summary>
+ /// Returns a new AttributeConstraint checking for the
+ /// presence of a particular attribute on an object.
+ /// </summary>
+ public static ResolvableConstraintExpression Attribute(Type expectedType)
+ {
+ return new ConstraintExpression().Attribute(expectedType);
+ }
+
+ /// <summary>
+ /// Returns a new AttributeConstraint checking for the
+ /// presence of a particular attribute on an object.
+ /// </summary>
+ public static ResolvableConstraintExpression Attribute<T>()
+ {
+ return Attribute(typeof(T));
+ }
+
+ #endregion
+
+ #region Member
+
+ /// <summary>
+ /// Returns a new CollectionContainsConstraint checking for the
+ /// presence of a particular object in the collection.
+ /// </summary>
+ public static CollectionContainsConstraint Member(object expected)
+ {
+ return new CollectionContainsConstraint(expected);
+ }
+
+ #endregion
+
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The IApplyToContext interface is implemented by attributes
+ /// that want to make changes to the execution context before
+ /// a test is run.
+ /// </summary>
+ public interface IApplyToContext
+ {
+ /// <summary>
+ /// Apply changes to the execution context
+ /// </summary>
+ /// <param name="context">The execution context</param>
+ void ApplyToContext(TestExecutionContext context);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The IApplyToTest interface is implemented by self-applying
+ /// attributes that modify the state of a test in some way.
+ /// </summary>
+ public interface IApplyToTest
+ {
+ /// <summary>
+ /// Modifies a test as defined for the specific attribute.
+ /// </summary>
+ /// <param name="test">The test to modify</param>
+ void ApplyToTest(Test test);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections;
+using System.Collections.Generic;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// CombiningStrategy is the abstract base for classes that
+ /// know how to combine values provided for individual test
+ /// parameters to create a set of test cases.
+ /// </summary>
+ public interface ICombiningStrategy
+ {
+ /// <summary>
+ /// Gets the test cases generated by the CombiningStrategy.
+ /// </summary>
+ /// <returns>The test cases.</returns>
+ IEnumerable<ITestCaseData> GetTestCases(IEnumerable[] sources);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using NUnit.Framework.Internal.Commands;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// ICommandWrapper is implemented by attributes and other
+ /// objects able to wrap a TestCommand with another command.
+ /// </summary>
+ /// <remarks>
+ /// Attributes or other objects should implement one of the
+ /// derived interfaces, rather than this one, since they
+ /// indicate in which part of the command chain the wrapper
+ /// should be applied.
+ /// </remarks>
+ public interface ICommandWrapper
+ {
+ /// <summary>
+ /// Wrap a command and return the result.
+ /// </summary>
+ /// <param name="command">The command to be wrapped</param>
+ /// <returns>The wrapped command</returns>
+ TestCommand Wrap(TestCommand command);
+ }
+
+ /// <summary>
+ /// Objects implementing this interface are used to wrap
+ /// the TestMethodCommand itself. They apply after SetUp
+ /// has been run and before TearDown.
+ /// </summary>
+ public interface IWrapTestMethod : ICommandWrapper
+ {
+ }
+
+ /// <summary>
+ /// Objects implementing this interface are used to wrap
+ /// the entire test, including SetUp and TearDown.
+ /// </summary>
+ public interface IWrapSetUpTearDown : ICommandWrapper
+ {
+ }
+}
--- /dev/null
+// **********************************************************************************
+// The MIT License (MIT)
+//
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy of
+// this software and associated documentation files (the "Software"), to deal in
+// the Software without restriction, including without limitation the rights to
+// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+// the Software, and to permit persons to whom the Software is furnished to do so,
+// subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all
+// copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+// **********************************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// Any ITest that implements this interface is at a level that the implementing
+ /// class should be disposed at the end of the test run
+ /// </summary>
+ internal interface IDisposableFixture
+ {
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+
+namespace NUnit.Framework.Interfaces
+{
+ using Internal;
+
+ /// <summary>
+ /// The IFixtureBuilder interface is exposed by a class that knows how to
+ /// build a TestFixture from one or more Types. In general, it is exposed
+ /// by an attribute, but may be implemented in a helper class used by the
+ /// attribute in some cases.
+ /// </summary>
+ public interface IFixtureBuilder
+ {
+ /// <summary>
+ /// Build one or more TestFixtures from type provided. At least one
+ /// non-null TestSuite must always be returned, since the method is
+ /// generally called because the user has marked the target class as
+ /// a fixture. If something prevents the fixture from being used, it
+ /// will be returned nonetheless, labelled as non-runnable.
+ /// </summary>
+ /// <param name="typeInfo">The type info of the fixture to be used.</param>
+ /// <returns>A TestSuite object or one derived from TestSuite.</returns>
+ // TODO: This should really return a TestFixture, but that requires changes to the Test hierarchy.
+ IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// IImplyFixture is an empty marker interface used by attributes like
+ /// TestAttribute that cause the class where they are used to be treated
+ /// as a TestFixture even without a TestFixtureAttribute.
+ ///
+ /// Marker interfaces are not usually considered a good practice, but
+ /// we use it here to avoid cluttering the attribute hierarchy with
+ /// classes that don't contain any extra implementation.
+ /// </summary>
+ public interface IImplyFixture
+ {
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The IMethodInfo class is used to encapsulate information
+ /// about a method in a platform-independent manner.
+ /// </summary>
+ public interface IMethodInfo : IReflectionInfo
+ {
+ #region Properties
+
+ /// <summary>
+ /// Gets the Type from which this method was reflected.
+ /// </summary>
+ ITypeInfo TypeInfo { get; }
+
+ /// <summary>
+ /// Gets the MethodInfo for this method.
+ /// </summary>
+ MethodInfo MethodInfo { get; }
+
+ /// <summary>
+ /// Gets the name of the method.
+ /// </summary>
+ string Name { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the method is abstract.
+ /// </summary>
+ bool IsAbstract { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the method is public.
+ /// </summary>
+ bool IsPublic { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the method contains unassigned generic type parameters.
+ /// </summary>
+ bool ContainsGenericParameters { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the method is a generic method.
+ /// </summary>
+ bool IsGenericMethod { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the MethodInfo represents the definition of a generic method.
+ /// </summary>
+ bool IsGenericMethodDefinition { get; }
+
+ /// <summary>
+ /// Gets the return Type of the method.
+ /// </summary>
+ ITypeInfo ReturnType { get; }
+
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Gets the parameters of the method.
+ /// </summary>
+ /// <returns></returns>
+ IParameterInfo[] GetParameters();
+
+ /// <summary>
+ /// Returns the Type arguments of a generic method or the Type parameters of a generic method definition.
+ /// </summary>
+ Type[] GetGenericArguments();
+
+ /// <summary>
+ /// Replaces the type parameters of the method with the array of types provided and returns a new IMethodInfo.
+ /// </summary>
+ /// <param name="typeArguments">The type arguments to be used</param>
+ /// <returns>A new IMethodInfo with the type arguments replaced</returns>
+ IMethodInfo MakeGenericMethod(params Type[] typeArguments);
+
+ /// <summary>
+ /// Invokes the method, converting any TargetInvocationException to an NUnitException.
+ /// </summary>
+ /// <param name="fixture">The object on which to invoke the method</param>
+ /// <param name="args">The argument list for the method</param>
+ /// <returns>The return value from the invoked method</returns>
+ object Invoke(object fixture, params object[] args);
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The IDataPointProvider interface is used by extensions
+ /// that provide data for a single test parameter.
+ /// </summary>
+ public interface IParameterDataProvider
+ {
+ /// <summary>
+ /// Determine whether any data is available for a parameter.
+ /// </summary>
+ /// <param name="parameter">An IParameterInfo representing one
+ /// argument to a parameterized test</param>
+ /// <returns>True if any data is available, otherwise false.</returns>
+ bool HasDataFor(IParameterInfo parameter);
+
+ /// <summary>
+ /// Return an IEnumerable providing data for use with the
+ /// supplied parameter.
+ /// </summary>
+ /// <param name="parameter">An IParameterInfo representing one
+ /// argument to a parameterized test</param>
+ /// <returns>An IEnumerable providing the required data</returns>
+ IEnumerable GetDataFor(IParameterInfo parameter);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The IParameterDataSource interface is implemented by types
+ /// that can provide data for a test method parameter.
+ /// </summary>
+ public interface IParameterDataSource
+ {
+ /// <summary>
+ /// Gets an enumeration of data items for use as arguments
+ /// for a test method parameter.
+ /// </summary>
+ /// <param name="parameter">The parameter for which data is needed</param>
+ /// <returns>An enumeration containing individual data items</returns>
+ IEnumerable GetData(IParameterInfo parameter);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The IParameterInfo interface is an abstraction of a .NET parameter.
+ /// </summary>
+ public interface IParameterInfo : IReflectionInfo
+ {
+ #region Properties
+
+#if !NETCF
+ /// <summary>
+ /// Gets a value indicating whether the parameter is optional
+ /// </summary>
+ bool IsOptional { get; }
+#endif
+
+ /// <summary>
+ /// Gets an IMethodInfo representing the method for which this is a parameter
+ /// </summary>
+ IMethodInfo Method { get; }
+
+ /// <summary>
+ /// Gets the underlying .NET ParameterInfo
+ /// </summary>
+ ParameterInfo ParameterInfo { get; }
+
+ /// <summary>
+ /// Gets the Type of the parameter
+ /// </summary>
+ Type ParameterType { get; }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// A PropertyBag represents a collection of name/value pairs
+ /// that allows duplicate entries with the same key. Methods
+ /// are provided for adding a new pair as well as for setting
+ /// a key to a single value. All keys are strings but _values
+ /// may be of any type. Null _values are not permitted, since
+ /// a null entry represents the absence of the key.
+ ///
+ /// The entries in a PropertyBag are of two kinds: those that
+ /// take a single value and those that take multiple _values.
+ /// However, the PropertyBag has no knowledge of which entries
+ /// fall into each category and the distinction is entirely
+ /// up to the code using the PropertyBag.
+ ///
+ /// When working with multi-valued properties, client code
+ /// should use the Add method to add name/value pairs and
+ /// indexing to retrieve a list of all _values for a given
+ /// key. For example:
+ ///
+ /// bag.Add("Tag", "one");
+ /// bag.Add("Tag", "two");
+ /// Assert.That(bag["Tag"],
+ /// Is.EqualTo(new string[] { "one", "two" }));
+ ///
+ /// When working with single-valued propeties, client code
+ /// should use the Set method to set the value and Get to
+ /// retrieve the value. The GetSetting methods may also be
+ /// used to retrieve the value in a type-safe manner while
+ /// also providing default. For example:
+ ///
+ /// bag.Set("Priority", "low");
+ /// bag.Set("Priority", "high"); // replaces value
+ /// Assert.That(bag.Get("Priority"),
+ /// Is.EqualTo("high"));
+ /// Assert.That(bag.GetSetting("Priority", "low"),
+ /// Is.EqualTo("high"));
+ /// </summary>
+ public interface IPropertyBag : IXmlNodeBuilder
+ {
+ /// <summary>
+ /// Adds a key/value pair to the property bag
+ /// </summary>
+ /// <param name="key">The key</param>
+ /// <param name="value">The value</param>
+ void Add(string key, object value);
+
+
+ /// <summary>
+ /// Sets the value for a key, removing any other
+ /// _values that are already in the property set.
+ /// </summary>
+ /// <param name="key"></param>
+ /// <param name="value"></param>
+ void Set(string key, object value);
+
+ /// <summary>
+ /// Gets a single value for a key, using the first
+ /// one if multiple _values are present and returning
+ /// null if the value is not found.
+ /// </summary>
+ object Get(string key);
+
+ /// <summary>
+ /// Gets a flag indicating whether the specified key has
+ /// any entries in the property set.
+ /// </summary>
+ /// <param name="key">The key to be checked</param>
+ /// <returns>True if their are _values present, otherwise false</returns>
+ bool ContainsKey(string key);
+
+ /// <summary>
+ /// Gets or sets the list of _values for a particular key
+ /// </summary>
+ /// <param name="key">The key for which the _values are to be retrieved or set</param>
+ IList this[string key] { get; set; }
+
+ /// <summary>
+ /// Gets a collection containing all the keys in the property set
+ /// </summary>
+ ICollection<string> Keys { get; }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The IReflectionInfo interface is implemented by NUnit wrapper objects that perform reflection.
+ /// </summary>
+ public interface IReflectionInfo
+ {
+ /// <summary>
+ /// Returns an array of custom attributes of the specified type applied to this object
+ /// </summary>
+ T[] GetCustomAttributes<T>(bool inherit) where T : class;
+
+ /// <summary>
+ /// Returns a value indicating whether an attribute of the specified type is defined on this object.
+ /// </summary>
+ bool IsDefined<T>(bool inherit);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections.Generic;
+using NUnit.Framework.Internal; // TODO: We shouldn't reference this in the interface
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The ISimpleTestBuilder interface is exposed by a class that knows how to
+ /// build a single TestMethod from a suitable MethodInfo Types. In general,
+ /// it is exposed by an attribute, but may be implemented in a helper class
+ /// used by the attribute in some cases.
+ /// </summary>
+ public interface ISimpleTestBuilder
+ {
+ /// <summary>
+ /// Build a TestMethod from the provided MethodInfo.
+ /// </summary>
+ /// <param name="method">The method to be used as a test</param>
+ /// <param name="suite">The TestSuite to which the method will be added</param>
+ /// <returns>A TestMethod object</returns>
+ TestMethod BuildFrom(IMethodInfo method, Test suite);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The ISuiteBuilder interface is exposed by a class that knows how to
+ /// build a suite from one or more Types.
+ /// </summary>
+ public interface ISuiteBuilder
+ {
+ /// <summary>
+ /// Examine the type and determine if it is suitable for
+ /// this builder to use in building a TestSuite.
+ ///
+ /// Note that returning false will cause the type to be ignored
+ /// in loading the tests. If it is desired to load the suite
+ /// but label it as non-runnable, ignored, etc., then this
+ /// method must return true.
+ /// </summary>
+ /// <param name="typeInfo">The type of the fixture to be used</param>
+ /// <returns>True if the type can be used to build a TestSuite</returns>
+ bool CanBuildFrom( ITypeInfo typeInfo );
+
+ /// <summary>
+ /// Build a TestSuite from type provided.
+ /// </summary>
+ /// <param name="typeInfo">The type of the fixture to be used</param>
+ /// <returns>A TestSuite</returns>
+ TestSuite BuildFrom( ITypeInfo typeInfo );
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// Common interface supported by all representations
+ /// of a test. Only includes informational fields.
+ /// The Run method is specifically excluded to allow
+ /// for data-only representations of a test.
+ /// </summary>
+ public interface ITest : IXmlNodeBuilder
+ {
+ /// <summary>
+ /// Gets the id of the test
+ /// </summary>
+ string Id { get; }
+
+ /// <summary>
+ /// Gets the name of the test
+ /// </summary>
+ string Name { get; }
+
+ /// <summary>
+ /// Gets the fully qualified name of the test
+ /// </summary>
+ string FullName { get; }
+
+ /// <summary>
+ /// Gets the name of the class containing this test. Returns
+ /// null if the test is not associated with a class.
+ /// </summary>
+ string ClassName { get; }
+
+ /// <summary>
+ /// Gets the name of the method implementing this test.
+ /// Returns null if the test is not implemented as a method.
+ /// </summary>
+ string MethodName { get; }
+
+ /// <summary>
+ /// Gets the Type of the test fixture, if applicable, or
+ /// null if no fixture type is associated with this test.
+ /// </summary>
+ ITypeInfo TypeInfo { get; }
+
+ /// <summary>
+ /// Gets an IMethod for the method implementing this test.
+ /// Returns null if the test is not implemented as a method.
+ /// </summary>
+ IMethodInfo Method { get; }
+
+ /// <summary>
+ /// Gets the RunState of the test, indicating whether it can be run.
+ /// </summary>
+ RunState RunState { get; }
+
+ /// <summary>
+ /// Count of the test cases ( 1 if this is a test case )
+ /// </summary>
+ int TestCaseCount { get; }
+
+ /// <summary>
+ /// Gets the properties of the test
+ /// </summary>
+ IPropertyBag Properties { get; }
+
+ /// <summary>
+ /// Gets the parent test, if any.
+ /// </summary>
+ /// <value>The parent test or null if none exists.</value>
+ ITest Parent { get; }
+
+ /// <summary>
+ /// Returns true if this is a test suite
+ /// </summary>
+ bool IsSuite { get; }
+
+ /// <summary>
+ /// Gets a bool indicating whether the current test
+ /// has any descendant tests.
+ /// </summary>
+ bool HasChildren { get; }
+
+ /// <summary>
+ /// Gets this test's child tests
+ /// </summary>
+ /// <value>A list of child tests</value>
+ System.Collections.Generic.IList<ITest> Tests { get; }
+
+ /// <summary>
+ /// Gets a fixture object for running this test.
+ /// </summary>
+ object Fixture { get; }
+ }
+}
+
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ using Interfaces;
+
+ /// <summary>
+ /// When implemented by an attribute, this interface implemented to provide actions to execute before and after tests.
+ /// </summary>
+ public interface ITestAction
+ {
+ /// <summary>
+ /// Executed before each test is run
+ /// </summary>
+ /// <param name="test">The test that is going to be run.</param>
+ void BeforeTest(ITest test);
+
+ /// <summary>
+ /// Executed after each test is run
+ /// </summary>
+ /// <param name="test">The test that has just been run.</param>
+ void AfterTest(ITest test);
+
+
+ /// <summary>
+ /// Provides the target for the action attribute
+ /// </summary>
+ /// <returns>The target for the action attribute</returns>
+ ActionTargets Targets { get; }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections.Generic;
+using NUnit.Framework.Internal; // TODO: We shouldn't reference this in the interface
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The ITestBuilder interface is exposed by a class that knows how to
+ /// build one or more TestMethods from a MethodInfo. In general, it is exposed
+ /// by an attribute, which has additional information available to provide
+ /// the necessary test parameters to distinguish the test cases built.
+ /// </summary>
+ public interface ITestBuilder
+ {
+ /// <summary>
+ /// Build one or more TestMethods from the provided MethodInfo.
+ /// </summary>
+ /// <param name="method">The method to be used as a test</param>
+ /// <param name="suite">The TestSuite to which the method will be added</param>
+ /// <returns>A TestMethod object</returns>
+ IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using NUnit.Framework.Internal;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The ITestCaseBuilder interface is exposed by a class that knows how to
+ /// build a test case from certain methods.
+ /// </summary>
+ /// <remarks>
+ /// This interface is not the same as the ITestCaseBuilder interface in NUnit 2.x.
+ /// We have reused the name because the two products don't interoperate at all.
+ /// </remarks>
+ public interface ITestCaseBuilder
+ {
+ /// <summary>
+ /// Examine the method and determine if it is suitable for
+ /// this builder to use in building a TestCase to be
+ /// included in the suite being populated.
+ ///
+ /// Note that returning false will cause the method to be ignored
+ /// in loading the tests. If it is desired to load the method
+ /// but label it as non-runnable, ignored, etc., then this
+ /// method must return true.
+ /// </summary>
+ /// <param name="method">The test method to examine</param>
+ /// <param name="suite">The suite being populated</param>
+ /// <returns>True is the builder can use this method</returns>
+ bool CanBuildFrom(IMethodInfo method, Test suite);
+
+ /// <summary>
+ /// Build a TestCase from the provided MethodInfo for
+ /// inclusion in the suite being constructed.
+ /// </summary>
+ /// <param name="method">The method to be used as a test case</param>
+ /// <param name="suite">The test suite being populated, or null</param>
+ /// <returns>A TestCase or null</returns>
+ Test BuildFrom(IMethodInfo method, Test suite);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFn
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The ITestCaseData interface is implemented by a class
+ /// that is able to return complete testcases for use by
+ /// a parameterized test method.
+ /// </summary>
+ public interface ITestCaseData : ITestData
+ {
+ /// <summary>
+ /// Gets the expected result of the test case
+ /// </summary>
+ object ExpectedResult { get; }
+
+ /// <summary>
+ /// Returns true if an expected result has been set
+ /// </summary>
+ bool HasExpectedResult { get; }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The ITestData interface is implemented by a class that
+ /// represents a single instance of a parameterized test.
+ /// </summary>
+ public interface ITestData
+ {
+ /// <summary>
+ /// Gets the name to be used for the test
+ /// </summary>
+ string TestName { get; }
+
+ /// <summary>
+ /// Gets the RunState for this test case.
+ /// </summary>
+ RunState RunState { get; }
+
+ /// <summary>
+ /// Gets the argument list to be provided to the test
+ /// </summary>
+ object[] Arguments { get; }
+
+ /// <summary>
+ /// Gets the property dictionary for the test case
+ /// </summary>
+ IPropertyBag Properties { get; }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// Interface to be implemented by filters applied to tests.
+ /// The filter applies when running the test, after it has been
+ /// loaded, since this is the only time an ITest exists.
+ /// </summary>
+ public interface ITestFilter : IXmlNodeBuilder
+ {
+ /// <summary>
+ /// Determine if a particular test passes the filter criteria. Pass
+ /// may examine the parents and/or descendants of a test, depending
+ /// on the semantics of the particular filter
+ /// </summary>
+ /// <param name="test">The test to which the filter is applied</param>
+ /// <returns>True if the test passes the filter, otherwise false</returns>
+ bool Pass(ITest test);
+
+ /// <summary>
+ /// Determine if a test matches the filter expicitly. That is, it must
+ /// be a direct match of the test itself or one of it's children.
+ /// </summary>
+ /// <param name="test">The test to which the filter is applied</param>
+ /// <returns>True if the test matches the filter explicityly, otherwise false</returns>
+ bool IsExplicitMatch(ITest test);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The ITestCaseData interface is implemented by a class
+ /// that is able to return the data required to create an
+ /// instance of a parameterized test fixture.
+ /// </summary>
+ public interface ITestFixtureData : ITestData
+ {
+ /// <summary>
+ /// Get the TypeArgs if separately set
+ /// </summary>
+ Type[] TypeArgs { get; }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The ITestListener interface is used internally to receive
+ /// notifications of significant events while a test is being
+ /// run. The events are propagated to clients by means of an
+ /// AsyncCallback. NUnit extensions may also monitor these events.
+ /// </summary>
+ public interface ITestListener
+ {
+ /// <summary>
+ /// Called when a test has just started
+ /// </summary>
+ /// <param name="test">The test that is starting</param>
+ void TestStarted(ITest test);
+
+ /// <summary>
+ /// Called when a test has finished
+ /// </summary>
+ /// <param name="result">The result of the test</param>
+ void TestFinished(ITestResult result);
+
+ /// <summary>
+ /// Called when a test produces output for immediate display
+ /// </summary>
+ /// <param name="output">A TestOutput object containing the text to display</param>
+ void TestOutput(TestOutput output);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The ITestResult interface represents the result of a test.
+ /// </summary>
+ public interface ITestResult : IXmlNodeBuilder
+ {
+ /// <summary>
+ /// Gets the ResultState of the test result, which
+ /// indicates the success or failure of the test.
+ /// </summary>
+ ResultState ResultState
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets the name of the test result
+ /// </summary>
+ string Name
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets the full name of the test result
+ /// </summary>
+ string FullName
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets the elapsed time for running the test in seconds
+ /// </summary>
+ double Duration
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets or sets the time the test started running.
+ /// </summary>
+ DateTime StartTime
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets or sets the time the test finished running.
+ /// </summary>
+ DateTime EndTime
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets the message associated with a test
+ /// failure or with not running the test
+ /// </summary>
+ string Message
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets any stacktrace associated with an
+ /// error or failure. Not available in
+ /// the Compact Framework 1.0.
+ /// </summary>
+ string StackTrace
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets the number of asserts executed
+ /// when running the test and all its children.
+ /// </summary>
+ int AssertCount
+ {
+ get;
+ }
+
+
+ /// <summary>
+ /// Gets the number of test cases that failed
+ /// when running the test and all its children.
+ /// </summary>
+ int FailCount
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that passed
+ /// when running the test and all its children.
+ /// </summary>
+ int PassCount
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that were skipped
+ /// when running the test and all its children.
+ /// </summary>
+ int SkipCount
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that were inconclusive
+ /// when running the test and all its children.
+ /// </summary>
+ int InconclusiveCount
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Indicates whether this result has any child results.
+ /// Accessing HasChildren should not force creation of the
+ /// Children collection in classes implementing this interface.
+ /// </summary>
+ bool HasChildren
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets the the collection of child results.
+ /// </summary>
+ IEnumerable<ITestResult> Children
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets the Test to which this result applies.
+ /// </summary>
+ ITest Test
+ {
+ get;
+ }
+
+ /// <summary>
+ /// Gets any text output written to this result.
+ /// </summary>
+ string Output
+ {
+ get;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The ITypeInfo interface is an abstraction of a .NET Type
+ /// </summary>
+ public interface ITypeInfo : IReflectionInfo
+ {
+ #region Properties
+
+ /// <summary>
+ /// Gets the underlying Type on which this ITypeInfo is based
+ /// </summary>
+ Type Type { get; }
+
+ /// <summary>
+ /// Gets the base type of this type as an ITypeInfo
+ /// </summary>
+ ITypeInfo BaseType { get; }
+
+ /// <summary>
+ /// Returns true if the Type wrapped is equal to the argument
+ /// </summary>
+ bool IsType(Type type);
+
+ /// <summary>
+ /// Gets the Name of the Type
+ /// </summary>
+ string Name { get; }
+
+ /// <summary>
+ /// Gets the FullName of the Type
+ /// </summary>
+ string FullName { get; }
+
+ /// <summary>
+ /// Gets the assembly in which the type is declared
+ /// </summary>
+ Assembly Assembly { get; }
+
+ /// <summary>
+ /// Gets the Namespace of the Type
+ /// </summary>
+ string Namespace { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the type is abstract.
+ /// </summary>
+ bool IsAbstract { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the Type is a generic Type
+ /// </summary>
+ bool IsGenericType { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the Type has generic parameters that have not been replaced by specific Types.
+ /// </summary>
+ bool ContainsGenericParameters { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the Type is a generic Type definition
+ /// </summary>
+ bool IsGenericTypeDefinition { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether the type is sealed.
+ /// </summary>
+ bool IsSealed { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether this type is a static class.
+ /// </summary>
+ bool IsStaticClass { get; }
+
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Get the display name for this typeInfo.
+ /// </summary>
+ string GetDisplayName();
+
+ /// <summary>
+ /// Get the display name for an oject of this type, constructed with specific arguments
+ /// </summary>
+ string GetDisplayName(object[] args);
+
+ /// <summary>
+ /// Returns a Type representing a generic type definition from which this Type can be constructed.
+ /// </summary>
+ Type GetGenericTypeDefinition();
+
+ /// <summary>
+ /// Returns a new ITypeInfo representing an instance of this generic Type using the supplied Type arguments
+ /// </summary>
+ ITypeInfo MakeGenericType(Type[] typeArgs);
+
+ /// <summary>
+ /// Returns a value indicating whether this type has a method with a specified public attribute
+ /// </summary>
+ bool HasMethodWithAttribute(Type attrType);
+
+ /// <summary>
+ /// Returns an array of IMethodInfos for methods of this Type
+ /// that match the specified flags.
+ /// </summary>
+ IMethodInfo[] GetMethods(BindingFlags flags);
+
+ /// <summary>
+ /// Gets the public constructor taking the specified argument Types
+ /// </summary>
+ ConstructorInfo GetConstructor(Type[] argTypes);
+
+ /// <summary>
+ /// Returns a value indicating whether this Type has a public constructor taking the specified argument Types.
+ /// </summary>
+ bool HasConstructor(Type[] argTypes);
+
+ /// <summary>
+ /// Construct an object of this Type, using the specified arguments.
+ /// </summary>
+ object Construct(object[] args);
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// An object implementing IXmlNodeBuilder is able to build
+ /// an XML representation of itself and any children.
+ /// </summary>
+ public interface IXmlNodeBuilder
+ {
+ /// <summary>
+ /// Returns a TNode representing the current object.
+ /// </summary>
+ /// <param name="recursive">If true, children are included where applicable</param>
+ /// <returns>A TNode representing the result</returns>
+ TNode ToXml(bool recursive);
+
+ /// <summary>
+ /// Returns a TNode representing the current object after
+ /// adding it as a child of the supplied parent node.
+ /// </summary>
+ /// <param name="parentNode">The parent node.</param>
+ /// <param name="recursive">If true, children are included, where applicable</param>
+ /// <returns></returns>
+ TNode AddToXml(TNode parentNode, bool recursive);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007-2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Text;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The ResultState class represents the outcome of running a test.
+ /// It contains two pieces of information. The Status of the test
+ /// is an enum indicating whether the test passed, failed, was
+ /// skipped or was inconclusive. The Label provides a more
+ /// detailed breakdown for use by client runners.
+ /// </summary>
+ public class ResultState
+ {
+ #region Constructors
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ResultState"/> class.
+ /// </summary>
+ /// <param name="status">The TestStatus.</param>
+ public ResultState(TestStatus status) : this (status, string.Empty, FailureSite.Test)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ResultState"/> class.
+ /// </summary>
+ /// <param name="status">The TestStatus.</param>
+ /// <param name="label">The label.</param>
+ public ResultState(TestStatus status, string label) : this (status, label, FailureSite.Test)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ResultState"/> class.
+ /// </summary>
+ /// <param name="status">The TestStatus.</param>
+ /// <param name="site">The stage at which the result was produced</param>
+ public ResultState(TestStatus status, FailureSite site) : this(status, string.Empty, site)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ResultState"/> class.
+ /// </summary>
+ /// <param name="status">The TestStatus.</param>
+ /// <param name="label">The label.</param>
+ /// <param name="site">The stage at which the result was produced</param>
+ public ResultState(TestStatus status, string label, FailureSite site)
+ {
+ Status = status;
+ Label = label == null ? string.Empty : label;
+ Site = site;
+ }
+
+ #endregion
+
+ #region Predefined ResultStates
+
+ /// <summary>
+ /// The result is inconclusive
+ /// </summary>
+ public readonly static ResultState Inconclusive = new ResultState(TestStatus.Inconclusive);
+
+ /// <summary>
+ /// The test has been skipped.
+ /// </summary>
+ public readonly static ResultState Skipped = new ResultState(TestStatus.Skipped);
+
+ /// <summary>
+ /// The test has been ignored.
+ /// </summary>
+ public readonly static ResultState Ignored = new ResultState(TestStatus.Skipped, "Ignored");
+
+ /// <summary>
+ /// The test was skipped because it is explicit
+ /// </summary>
+ public readonly static ResultState Explicit = new ResultState(TestStatus.Skipped, "Explicit");
+
+ /// <summary>
+ /// The test succeeded
+ /// </summary>
+ public readonly static ResultState Success = new ResultState(TestStatus.Passed);
+
+ /// <summary>
+ /// The test failed
+ /// </summary>
+ public readonly static ResultState Failure = new ResultState(TestStatus.Failed);
+
+ /// <summary>
+ /// The test encountered an unexpected exception
+ /// </summary>
+ public readonly static ResultState Error = new ResultState(TestStatus.Failed, "Error");
+
+ /// <summary>
+ /// The test was cancelled by the user
+ /// </summary>
+ public readonly static ResultState Cancelled = new ResultState(TestStatus.Failed, "Cancelled");
+
+ /// <summary>
+ /// The test was not runnable.
+ /// </summary>
+ public readonly static ResultState NotRunnable = new ResultState(TestStatus.Failed, "Invalid");
+
+ /// <summary>
+ /// A suite failed because one or more child tests failed or had errors
+ /// </summary>
+ public readonly static ResultState ChildFailure = ResultState.Failure.WithSite(FailureSite.Child);
+
+ /// <summary>
+ /// A suite failed in its OneTimeSetUp
+ /// </summary>
+ public readonly static ResultState SetUpFailure = ResultState.Failure.WithSite(FailureSite.SetUp);
+
+ /// <summary>
+ /// A suite had an unexpected exception in its OneTimeSetUp
+ /// </summary>
+ public readonly static ResultState SetUpError = ResultState.Error.WithSite(FailureSite.SetUp);
+
+ /// <summary>
+ /// A suite had an unexpected exception in its OneTimeDown
+ /// </summary>
+ public readonly static ResultState TearDownError = ResultState.Error.WithSite(FailureSite.TearDown);
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Gets the TestStatus for the test.
+ /// </summary>
+ /// <value>The status.</value>
+ public TestStatus Status { get; private set; }
+
+ /// <summary>
+ /// Gets the label under which this test result is
+ /// categorized, if any.
+ /// </summary>
+ public string Label { get; private set; }
+
+ /// <summary>
+ /// Gets the stage of test execution in which
+ /// the failure or other result took place.
+ /// </summary>
+ public FailureSite Site { get; private set; }
+
+ /// <summary>
+ /// Get a new ResultState, which is the same as the current
+ /// one but with the FailureSite set to the specified value.
+ /// </summary>
+ /// <param name="site">The FailureSite to use</param>
+ /// <returns>A new ResultState</returns>
+ public ResultState WithSite(FailureSite site)
+ {
+ return new ResultState(this.Status, this.Label, site);
+ }
+
+ #endregion
+
+ #region Equals Override
+
+ /// <summary>
+ /// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
+ /// </summary>
+ /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
+ /// <returns>
+ /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
+ /// </returns>
+ public override bool Equals(object obj)
+ {
+ var other = obj as ResultState;
+ if (other == null) return false;
+
+ return Status.Equals(other.Status) && Label.Equals(other.Label) && Site.Equals(other.Site);
+ }
+
+ /// <summary>
+ /// Returns a hash code for this instance.
+ /// </summary>
+ /// <returns>
+ /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
+ /// </returns>
+ public override int GetHashCode()
+ {
+ return (int)Status << 8 + (int)Site ^ Label.GetHashCode(); ;
+ }
+
+ #endregion
+
+ #region ToString Override
+
+ /// <summary>
+ /// Returns a <see cref="System.String"/> that represents this instance.
+ /// </summary>
+ /// <returns>
+ /// A <see cref="System.String"/> that represents this instance.
+ /// </returns>
+ public override string ToString()
+ {
+ var sb = new StringBuilder(Status.ToString());
+
+ if (Label != null && Label.Length > 0)
+ sb.AppendFormat(":{0}", Label);
+ if (Site != FailureSite.Test)
+ sb.AppendFormat("({0})", Site.ToString());
+
+ return sb.ToString();
+ }
+
+ #endregion
+ }
+
+ /// <summary>
+ /// The FailureSite enum indicates the stage of a test
+ /// in which an error or failure occurred.
+ /// </summary>
+ public enum FailureSite
+ {
+ /// <summary>
+ /// Failure in the test itself
+ /// </summary>
+ Test,
+
+ /// <summary>
+ /// Failure in the SetUp method
+ /// </summary>
+ SetUp,
+
+ /// <summary>
+ /// Failure in the TearDown method
+ /// </summary>
+ TearDown,
+
+ /// <summary>
+ /// Failure of a parent test
+ /// </summary>
+ Parent,
+
+ /// <summary>
+ /// Failure of a child test
+ /// </summary>
+ Child
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The RunState enum indicates whether a test can be executed.
+ /// </summary>
+ public enum RunState
+ {
+ /// <summary>
+ /// The test is not runnable.
+ /// </summary>
+ NotRunnable,
+
+ /// <summary>
+ /// The test is runnable.
+ /// </summary>
+ Runnable,
+
+ /// <summary>
+ /// The test can only be run explicitly
+ /// </summary>
+ Explicit,
+
+ /// <summary>
+ /// The test has been skipped. This value may
+ /// appear on a Test when certain attributes
+ /// are used to skip the test.
+ /// </summary>
+ Skipped,
+
+ /// <summary>
+ /// The test has been ignored. May appear on
+ /// a Test, when the IgnoreAttribute is used.
+ /// </summary>
+ Ignored
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Text.RegularExpressions;
+using System.Xml;
+
+#if PORTABLE || SILVERLIGHT
+using System.Xml.Linq;
+#endif
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// TNode represents a single node in the XML representation
+ /// of a Test or TestResult. It replaces System.Xml.XmlNode and
+ /// System.Xml.Linq.XElement, providing a minimal set of methods
+ /// for operating on the XML in a platform-independent manner.
+ /// </summary>
+ public class TNode
+ {
+ #region Constructors
+
+ /// <summary>
+ /// Constructs a new instance of TNode
+ /// </summary>
+ /// <param name="name">The name of the node</param>
+ public TNode(string name)
+ {
+ Name = name;
+ Attributes = new AttributeDictionary();
+ ChildNodes = new NodeList();
+ }
+
+ /// <summary>
+ /// Constructs a new instance of TNode with a value
+ /// </summary>
+ /// <param name="name">The name of the node</param>
+ /// <param name="value">The text content of the node</param>
+ public TNode(string name, string value) : this(name, value, false) { }
+
+ /// <summary>
+ /// Constructs a new instance of TNode with a value
+ /// </summary>
+ /// <param name="name">The name of the node</param>
+ /// <param name="value">The text content of the node</param>
+ /// <param name="valueIsCDATA">Flag indicating whether to use CDATA when writing the text</param>
+ public TNode(string name, string value, bool valueIsCDATA)
+ : this(name)
+ {
+ Value = value;
+ ValueIsCDATA = valueIsCDATA;
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Gets the name of the node
+ /// </summary>
+ public string Name { get; private set; }
+
+ /// <summary>
+ /// Gets the value of the node
+ /// </summary>
+ public string Value { get; set; }
+
+ /// <summary>
+ /// Gets a flag indicating whether the value should be output using CDATA.
+ /// </summary>
+ public bool ValueIsCDATA { get; private set; }
+
+ /// <summary>
+ /// Gets the dictionary of attributes
+ /// </summary>
+ public AttributeDictionary Attributes { get; private set; }
+
+ /// <summary>
+ /// Gets a list of child nodes
+ /// </summary>
+ public NodeList ChildNodes { get; private set; }
+
+ /// <summary>
+ /// Gets the first ChildNode
+ /// </summary>
+ public TNode FirstChild
+ {
+ get { return ChildNodes.Count == 0 ? null : ChildNodes[0]; }
+ }
+
+ /// <summary>
+ /// Gets the XML representation of this node.
+ /// </summary>
+ public string OuterXml
+ {
+ get
+ {
+ var stringWriter = new System.IO.StringWriter();
+ var settings = new XmlWriterSettings();
+ settings.ConformanceLevel = ConformanceLevel.Fragment;
+
+ using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
+ {
+ WriteTo(xmlWriter);
+ }
+
+ return stringWriter.ToString();
+ }
+ }
+
+ #endregion
+
+ #region Static Methods
+
+ /// <summary>
+ /// Create a TNode from it's XML text representation
+ /// </summary>
+ /// <param name="xmlText">The XML text to be parsed</param>
+ /// <returns>A TNode</returns>
+ public static TNode FromXml(string xmlText)
+ {
+#if PORTABLE || SILVERLIGHT
+ return FromXml(XElement.Parse(xmlText));
+#else
+ var doc = new XmlDocument();
+ doc.LoadXml(xmlText);
+ return FromXml(doc.FirstChild);
+#endif
+ }
+
+ #endregion
+
+ #region Instance Methods
+
+ /// <summary>
+ /// Adds a new element as a child of the current node and returns it.
+ /// </summary>
+ /// <param name="name">The element name.</param>
+ /// <returns>The newly created child element</returns>
+ public TNode AddElement(string name)
+ {
+ TNode childResult = new TNode(name);
+ ChildNodes.Add(childResult);
+ return childResult;
+ }
+
+ /// <summary>
+ /// Adds a new element with a value as a child of the current node and returns it.
+ /// </summary>
+ /// <param name="name">The element name</param>
+ /// <param name="value">The text content of the new element</param>
+ /// <returns>The newly created child element</returns>
+ public TNode AddElement(string name, string value)
+ {
+ TNode childResult = new TNode(name, EscapeInvalidXmlCharacters(value));
+ ChildNodes.Add(childResult);
+ return childResult;
+ }
+
+ /// <summary>
+ /// Adds a new element with a value as a child of the current node and returns it.
+ /// The value will be output using a CDATA section.
+ /// </summary>
+ /// <param name="name">The element name</param>
+ /// <param name="value">The text content of the new element</param>
+ /// <returns>The newly created child element</returns>
+ public TNode AddElementWithCDATA(string name, string value)
+ {
+ TNode childResult = new TNode(name, EscapeInvalidXmlCharacters(value), true);
+ ChildNodes.Add(childResult);
+ return childResult;
+ }
+
+ /// <summary>
+ /// Adds an attribute with a specified name and value to the XmlNode.
+ /// </summary>
+ /// <param name="name">The name of the attribute.</param>
+ /// <param name="value">The value of the attribute.</param>
+ public void AddAttribute(string name, string value)
+ {
+ Attributes.Add(name, EscapeInvalidXmlCharacters(value));
+ }
+
+ /// <summary>
+ /// Finds a single descendant of this node matching an xpath
+ /// specification. The format of the specification is
+ /// limited to what is needed by NUnit and its tests.
+ /// </summary>
+ /// <param name="xpath"></param>
+ /// <returns></returns>
+ public TNode SelectSingleNode(string xpath)
+ {
+ NodeList nodes = SelectNodes(xpath);
+
+ return nodes.Count > 0
+ ? nodes[0] as TNode
+ : null;
+ }
+
+ /// <summary>
+ /// Finds all descendants of this node matching an xpath
+ /// specification. The format of the specification is
+ /// limited to what is needed by NUnit and its tests.
+ /// </summary>
+ public NodeList SelectNodes(string xpath)
+ {
+ NodeList nodeList = new NodeList();
+ nodeList.Add(this);
+
+ return ApplySelection(nodeList, xpath);
+ }
+
+ /// <summary>
+ /// Writes the XML representation of the node to an XmlWriter
+ /// </summary>
+ /// <param name="writer"></param>
+ public void WriteTo(XmlWriter writer)
+ {
+ writer.WriteStartElement(Name);
+
+ foreach (string name in Attributes.Keys)
+ writer.WriteAttributeString(name, Attributes[name]);
+
+ if (Value != null)
+ if (ValueIsCDATA)
+ WriteCDataTo(writer);
+ else
+ writer.WriteString(Value);
+
+ foreach (TNode node in ChildNodes)
+ node.WriteTo(writer);
+
+ writer.WriteEndElement();
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+#if PORTABLE || SILVERLIGHT
+ private static TNode FromXml(XElement xElement)
+ {
+ TNode tNode = new TNode(xElement.Name.ToString(), xElement.Value);
+
+ foreach (var attr in xElement.Attributes())
+ tNode.AddAttribute(attr.Name.ToString(), attr.Value);
+
+ foreach (var child in xElement.Elements())
+ tNode.ChildNodes.Add(FromXml(child));
+
+ return tNode;
+ }
+#else
+ private static TNode FromXml(XmlNode xmlNode)
+ {
+ TNode tNode = new TNode(xmlNode.Name, xmlNode.InnerText);
+
+ foreach (XmlAttribute attr in xmlNode.Attributes)
+ tNode.AddAttribute(attr.Name, attr.Value);
+
+ foreach (XmlNode child in xmlNode.ChildNodes)
+ if (child.NodeType == XmlNodeType.Element)
+ tNode.ChildNodes.Add(FromXml(child));
+
+ return tNode;
+ }
+#endif
+
+ private static NodeList ApplySelection(NodeList nodeList, string xpath)
+ {
+ Guard.ArgumentNotNullOrEmpty(xpath, "xpath");
+ if (xpath[0] == '/')
+ throw new ArgumentException("XPath expressions starting with '/' are not supported", "xpath");
+ if (xpath.IndexOf("//") >= 0)
+ throw new ArgumentException("XPath expressions with '//' are not supported", "xpath");
+
+ string head = xpath;
+ string tail = null;
+
+ int slash = xpath.IndexOf('/');
+ if (slash >= 0)
+ {
+ head = xpath.Substring(0, slash);
+ tail = xpath.Substring(slash + 1);
+ }
+
+ NodeList resultNodes = new NodeList();
+ NodeFilter filter = new NodeFilter(head);
+
+ foreach(TNode node in nodeList)
+ foreach (TNode childNode in node.ChildNodes)
+ if (filter.Pass(childNode))
+ resultNodes.Add(childNode);
+
+ return tail != null
+ ? ApplySelection(resultNodes, tail)
+ : resultNodes;
+ }
+
+ private static readonly Regex InvalidXmlCharactersRegex = new Regex("[^\u0009\u000a\u000d\u0020-\ufffd]|([\ud800-\udbff](?![\udc00-\udfff]))|((?<![\ud800-\udbff])[\udc00-\udfff])");
+ private static string EscapeInvalidXmlCharacters(string str)
+ {
+ if (str == null) return null;
+
+ // Based on the XML spec http://www.w3.org/TR/xml/#charsets
+ // For detailed explanation of the regex see http://mnaoumov.wordpress.com/2014/06/15/escaping-invalid-xml-unicode-characters/
+
+ return InvalidXmlCharactersRegex.Replace(str, match => CharToUnicodeSequence(match.Value[0]));
+ }
+
+ private static string CharToUnicodeSequence(char symbol)
+ {
+ return string.Format("\\u{0}", ((int)symbol).ToString("x4"));
+ }
+
+ private void WriteCDataTo(XmlWriter writer)
+ {
+ int start = 0;
+ string text = Value;
+
+ while (true)
+ {
+ int illegal = text.IndexOf("]]>", start);
+ if (illegal < 0)
+ break;
+ writer.WriteCData(text.Substring(start, illegal - start + 2));
+ start = illegal + 2;
+ if (start >= text.Length)
+ return;
+ }
+
+ if (start > 0)
+ writer.WriteCData(text.Substring(start));
+ else
+ writer.WriteCData(text);
+ }
+
+ #endregion
+
+ #region Nested NodeFilter class
+
+ class NodeFilter
+ {
+ private string _nodeName;
+ private string _propName;
+ private string _propValue;
+
+ public NodeFilter(string xpath)
+ {
+ _nodeName = xpath;
+
+ int lbrack = xpath.IndexOf('[');
+ if (lbrack >= 0)
+ {
+ if (!xpath.EndsWith("]"))
+ throw new ArgumentException("Invalid property expression", "xpath");
+
+ _nodeName = xpath.Substring(0, lbrack);
+ string filter = xpath.Substring(lbrack+1, xpath.Length - lbrack - 2);
+
+ int equals = filter.IndexOf('=');
+ if (equals < 0 || filter[0] != '@')
+ throw new ArgumentException("Invalid property expression", "xpath");
+
+ _propName = filter.Substring(1, equals - 1).Trim();
+ _propValue = filter.Substring(equals + 1).Trim(new char[] { ' ', '"', '\'' });
+ }
+ }
+
+ public bool Pass(TNode node)
+ {
+ if (node.Name != _nodeName)
+ return false;
+
+ if (_propName == null)
+ return true;
+
+ return node.Attributes[_propName] == _propValue;
+ }
+ }
+
+ #endregion
+ }
+
+ /// <summary>
+ /// Class used to represent a list of XmlResults
+ /// </summary>
+ public class NodeList : System.Collections.Generic.List<TNode>
+ {
+ }
+
+ /// <summary>
+ /// Class used to represent the attributes of a node
+ /// </summary>
+ public class AttributeDictionary : System.Collections.Generic.Dictionary<string, string>
+ {
+ /// <summary>
+ /// Gets or sets the value associated with the specified key.
+ /// Overridden to return null if attribute is not found.
+ /// </summary>
+ /// <param name="key">The key.</param>
+ /// <returns>Value of the attribute or null</returns>
+ public new string this[string key]
+ {
+ get
+ {
+ string value;
+
+ if (TryGetValue(key, out value))
+ return value;
+
+ return null;
+ }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The TestOutput class holds a unit of output from
+ /// a test to a specific output stream
+ /// </summary>
+ public class TestOutput
+ {
+ /// <summary>
+ /// Construct with text, ouput destination type and
+ /// the name of the test that produced the output.
+ /// </summary>
+ /// <param name="text">Text to be output</param>
+ /// <param name="stream">Name of the stream or channel to which the text should be written</param>
+ /// <param name="testName">FullName of test that produced the output</param>
+ public TestOutput(string text, string stream, string testName)
+ {
+ Text = text;
+ Stream = stream;
+ TestName = testName;
+ }
+
+ /// <summary>
+ /// Return string representation of the object for debugging
+ /// </summary>
+ /// <returns></returns>
+ public override string ToString()
+ {
+ return Stream + ": " + Text;
+ }
+
+ /// <summary>
+ /// Get the text
+ /// </summary>
+ public string Text { get; private set; }
+
+ /// <summary>
+ /// Get the output type
+ /// </summary>
+ public string Stream { get; private set; }
+
+ /// <summary>
+ /// Get the name of the test that created the output
+ /// </summary>
+ public string TestName { get; private set; }
+
+ /// <summary>
+ /// Convert the TestOutput object to an XML string
+ /// </summary>
+ public string ToXml()
+ {
+ return TestName != null
+ ? string.Format("<test-output stream='{0}' testname='{1}'>{2}</test-output>", Stream, TestName, Text)
+ : string.Format("<test-output stream='{0}'>{1}</test-output>", Stream, Text);
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Interfaces
+{
+ /// <summary>
+ /// The TestStatus enum indicates the result of running a test
+ /// </summary>
+ public enum TestStatus
+ {
+ /// <summary>
+ /// The test was inconclusive
+ /// </summary>
+ Inconclusive,
+
+ /// <summary>
+ /// The test has skipped
+ /// </summary>
+ Skipped,
+
+ /// <summary>
+ /// The test succeeded
+ /// </summary>
+ Passed,
+
+ /// <summary>
+ /// The test failed
+ /// </summary>
+ Failed
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Compatibility;
+
+#if PORTABLE
+using System.Linq;
+#endif
+
+namespace NUnit.Framework.Internal
+{
+ using Interfaces;
+
+ internal class ActionsHelper
+ {
+ public static void ExecuteBeforeActions(IEnumerable<ITestAction> actions, ITest test)
+ {
+ ExecuteActions(ActionPhase.Before, actions, test);
+ }
+
+ public static void ExecuteAfterActions(IEnumerable<ITestAction> actions, ITest test)
+ {
+ ExecuteActions(ActionPhase.After, actions, test);
+ }
+
+ private static void ExecuteActions(ActionPhase phase, IEnumerable<ITestAction> actions, ITest test)
+ {
+ if (actions == null)
+ return;
+
+ foreach (ITestAction action in GetFilteredAndSortedActions(actions, phase))
+ {
+ if(phase == ActionPhase.Before)
+ action.BeforeTest(test);
+ else
+ action.AfterTest(test);
+ }
+ }
+
+#if PORTABLE
+ //public static ITestAction[] GetActionsFromAttributeProvider(Assembly attributeProvider)
+ //{
+ // if (attributeProvider == null)
+ // return new ITestAction[0];
+
+ // var actions = attributeProvider.GetAttributes<ITestAction>().ToList();
+ // actions.Sort(SortByTargetDescending);
+
+ // return actions.ToArray();
+ //}
+
+ //public static ITestAction[] GetActionsFromAttributeProvider(MemberInfo attributeProvider)
+ //{
+ // if (attributeProvider == null)
+ // return new ITestAction[0];
+
+ // var actions = attributeProvider.GetAttributes<ITestAction>(false).ToList();
+ // actions.Sort(SortByTargetDescending);
+
+ // return actions.ToArray();
+ //}
+#else
+ public static ITestAction[] GetActionsFromAttributeProvider(ICustomAttributeProvider attributeProvider)
+ {
+ if (attributeProvider == null)
+ return new ITestAction[0];
+
+ var actions = new List<ITestAction>((ITestAction[])attributeProvider.GetCustomAttributes(typeof(ITestAction), false));
+ actions.Sort(SortByTargetDescending);
+
+ return actions.ToArray();
+ }
+#endif
+
+ //public static ITestAction[] GetActionsFromTypesAttributes(Type type)
+ //{
+ // if(type == null)
+ // return new ITestAction[0];
+
+ // if(type == typeof(object))
+ // return new ITestAction[0];
+
+ // var actions = new List<ITestAction>();
+
+ // actions.AddRange(GetActionsFromTypesAttributes(type.GetTypeInfo().BaseType));
+
+ // Type[] declaredInterfaces = GetDeclaredInterfaces(type);
+
+ // foreach(Type interfaceType in declaredInterfaces)
+ // actions.AddRange(GetActionsFromAttributeProvider(interfaceType.GetTypeInfo()));
+
+ // actions.AddRange(GetActionsFromAttributeProvider(type.GetTypeInfo()));
+
+ // return actions.ToArray();
+ //}
+
+ private static Type[] GetDeclaredInterfaces(Type type)
+ {
+ List<Type> interfaces = new List<Type>(type.GetInterfaces());
+
+ if (type.GetTypeInfo().BaseType == typeof(object))
+ return interfaces.ToArray();
+
+ List<Type> baseInterfaces = new List<Type>(type.GetTypeInfo().BaseType.GetInterfaces());
+ List<Type> declaredInterfaces = new List<Type>();
+
+ foreach (Type interfaceType in interfaces)
+ {
+ if (!baseInterfaces.Contains(interfaceType))
+ declaredInterfaces.Add(interfaceType);
+ }
+
+ return declaredInterfaces.ToArray();
+ }
+
+ private static ITestAction[] GetFilteredAndSortedActions(IEnumerable<ITestAction> actions, ActionPhase phase)
+ {
+ var filteredActions = new List<ITestAction>();
+ foreach (var actionItem in actions)
+ {
+ if (filteredActions.Contains(actionItem) != true)
+ filteredActions.Add(actionItem);
+ }
+
+ if(phase == ActionPhase.After)
+ filteredActions.Reverse();
+
+ return filteredActions.ToArray();
+ }
+
+ private static int SortByTargetDescending(ITestAction x, ITestAction y)
+ {
+ return y.Targets.CompareTo(x.Targets);
+ }
+
+ private enum ActionPhase
+ {
+ Before,
+ After
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2013 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if NET_4_0 || NET_4_5 || PORTABLE
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Threading;
+using NUnit.Compatibility;
+
+#if NET_4_5 || PORTABLE
+using System.Runtime.ExceptionServices;
+#endif
+
+namespace NUnit.Framework.Internal
+{
+ internal abstract class AsyncInvocationRegion : IDisposable
+ {
+ private const string TaskTypeName = "System.Threading.Tasks.Task";
+ private const string AsyncAttributeTypeName = "System.Runtime.CompilerServices.AsyncStateMachineAttribute";
+
+ private AsyncInvocationRegion()
+ {
+ }
+
+ public static AsyncInvocationRegion Create(Delegate @delegate)
+ {
+#if PORTABLE
+ return Create(@delegate.GetMethodInfo());
+#else
+ return Create(@delegate.Method);
+#endif
+ }
+
+ public static AsyncInvocationRegion Create(MethodInfo method)
+ {
+ if (!IsAsyncOperation(method))
+ throw new ArgumentException(@"Either asynchronous support is not available or an attempt
+at wrapping a non-async method invocation in an async region was done");
+
+ if (method.ReturnType == typeof(void))
+ throw new ArgumentException("'async void' methods are not supported, please use 'async Task' instead");
+
+ return new AsyncTaskInvocationRegion();
+ }
+
+ public static bool IsAsyncOperation(MethodInfo method)
+ {
+ var name = method.ReturnType.FullName;
+ if (name == null) return false;
+ return name.StartsWith(TaskTypeName) ||
+ method.GetCustomAttributes(false).Any(attr => AsyncAttributeTypeName == attr.GetType().FullName);
+ }
+
+ public static bool IsAsyncOperation(Delegate @delegate)
+ {
+#if PORTABLE
+ return IsAsyncOperation(@delegate.GetMethodInfo());
+#else
+ return IsAsyncOperation(@delegate.Method);
+#endif
+ }
+
+ /// <summary>
+ /// Waits for pending asynchronous operations to complete, if appropriate,
+ /// and returns a proper result of the invocation by unwrapping task results
+ /// </summary>
+ /// <param name="invocationResult">The raw result of the method invocation</param>
+ /// <returns>The unwrapped result, if necessary</returns>
+ public abstract object WaitForPendingOperationsToComplete(object invocationResult);
+
+ public virtual void Dispose()
+ { }
+
+ private class AsyncTaskInvocationRegion : AsyncInvocationRegion
+ {
+ private const string TaskWaitMethod = "Wait";
+ private const string TaskResultProperty = "Result";
+ private const string VoidTaskResultType = "VoidTaskResult";
+ private const string SystemAggregateException = "System.AggregateException";
+ private const string InnerExceptionsProperty = "InnerExceptions";
+ private const BindingFlags TaskResultPropertyBindingFlags = BindingFlags.Instance | BindingFlags.Public;
+
+ public override object WaitForPendingOperationsToComplete(object invocationResult)
+ {
+ try
+ {
+ invocationResult.GetType().GetMethod(TaskWaitMethod, new Type[0]).Invoke(invocationResult, null);
+ }
+ catch (TargetInvocationException e)
+ {
+ IList<Exception> innerExceptions = GetAllExceptions(e.InnerException);
+ ExceptionHelper.Rethrow(innerExceptions[0]);
+ }
+ var args = invocationResult.GetType().GetGenericArguments();
+ if (args != null && args.Length == 1 && args[0].Name == VoidTaskResultType)
+ {
+ return null;
+ }
+
+ PropertyInfo taskResultProperty = invocationResult.GetType().GetProperty(TaskResultProperty, TaskResultPropertyBindingFlags);
+
+ return taskResultProperty != null ? taskResultProperty.GetValue(invocationResult, null) : invocationResult;
+ }
+
+ private static IList<Exception> GetAllExceptions(Exception exception)
+ {
+ if (SystemAggregateException.Equals(exception.GetType().FullName))
+ return (IList<Exception>)exception.GetType().GetProperty(InnerExceptionsProperty).GetValue(exception, null);
+
+ return new Exception[] { exception };
+ }
+ }
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Builders
+{
+ /// <summary>
+ /// CombinatorialStrategy creates test cases by using all possible
+ /// combinations of the parameter data.
+ /// </summary>
+ public class CombinatorialStrategy : ICombiningStrategy
+ {
+ /// <summary>
+ /// Gets the test cases generated by the CombiningStrategy.
+ /// </summary>
+ /// <returns>The test cases.</returns>
+ public IEnumerable<ITestCaseData> GetTestCases(IEnumerable[] sources)
+ {
+ List<ITestCaseData> testCases = new List<ITestCaseData>();
+ IEnumerator[] enumerators = new IEnumerator[sources.Length];
+ int index = -1;
+
+ for (; ; )
+ {
+ while (++index < sources.Length)
+ {
+ enumerators[index] = sources[index].GetEnumerator();
+ if (!enumerators[index].MoveNext())
+ return testCases;
+ }
+
+ object[] testdata = new object[sources.Length];
+
+ for (int i = 0; i < sources.Length; i++)
+ testdata[i] = enumerators[i].Current;
+
+ TestCaseParameters parms = new TestCaseParameters(testdata);
+ testCases.Add(parms);
+
+ index = sources.Length;
+
+ while (--index >= 0 && !enumerators[index].MoveNext()) ;
+
+ if (index < 0) break;
+ }
+
+ return testCases;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+using System.Collections;
+using System.Collections.Generic;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Builders
+{
+ /// <summary>
+ /// Provides data from fields marked with the DatapointAttribute or the
+ /// DatapointsAttribute.
+ /// </summary>
+ public class DatapointProvider : IParameterDataProvider
+ {
+ #region IDataPointProvider Members
+
+ /// <summary>
+ /// Determine whether any data is available for a parameter.
+ /// </summary>
+ /// <param name="parameter">A ParameterInfo representing one
+ /// argument to a parameterized test</param>
+ /// <returns>
+ /// True if any data is available, otherwise false.
+ /// </returns>
+ public bool HasDataFor(IParameterInfo parameter)
+ {
+ var method = parameter.Method;
+ if (!method.IsDefined<TheoryAttribute>(true))
+ return false;
+
+ Type parameterType = parameter.ParameterType;
+ if (parameterType == typeof(bool) || parameterType.GetTypeInfo().IsEnum)
+ return true;
+
+ Type containingType = method.TypeInfo.Type;
+ foreach (MemberInfo member in containingType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy))
+ {
+ if (member.IsDefined(typeof(DatapointAttribute), true) &&
+ GetTypeFromMemberInfo(member) == parameterType)
+ return true;
+ else if (member.IsDefined(typeof(DatapointSourceAttribute), true) &&
+ GetElementTypeFromMemberInfo(member) == parameterType)
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Return an IEnumerable providing data for use with the
+ /// supplied parameter.
+ /// </summary>
+ /// <param name="parameter">A ParameterInfo representing one
+ /// argument to a parameterized test</param>
+ /// <returns>
+ /// An IEnumerable providing the required data
+ /// </returns>
+ public System.Collections.IEnumerable GetDataFor(IParameterInfo parameter)
+ {
+ var datapoints = new List<object>();
+
+ Type parameterType = parameter.ParameterType;
+ Type fixtureType = parameter.Method.TypeInfo.Type;
+
+ foreach (MemberInfo member in fixtureType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy))
+ {
+ if (member.IsDefined(typeof(DatapointAttribute), true))
+ {
+ var field = member as FieldInfo;
+ if (GetTypeFromMemberInfo(member) == parameterType && field != null)
+ {
+ if (field.IsStatic)
+ datapoints.Add(field.GetValue(null));
+ else
+ datapoints.Add(field.GetValue(ProviderCache.GetInstanceOf(fixtureType)));
+ }
+ }
+ else if (member.IsDefined(typeof(DatapointSourceAttribute), true))
+ {
+ if (GetElementTypeFromMemberInfo(member) == parameterType)
+ {
+ object instance;
+
+ FieldInfo field = member as FieldInfo;
+ PropertyInfo property = member as PropertyInfo;
+ MethodInfo method = member as MethodInfo;
+ if (field != null)
+ {
+ instance = field.IsStatic ? null : ProviderCache.GetInstanceOf(fixtureType);
+ foreach (object data in (IEnumerable)field.GetValue(instance))
+ datapoints.Add(data);
+ }
+ else if (property != null)
+ {
+ MethodInfo getMethod = property.GetGetMethod(true);
+ instance = getMethod.IsStatic ? null : ProviderCache.GetInstanceOf(fixtureType);
+ foreach (object data in (IEnumerable)property.GetValue(instance, null))
+ datapoints.Add(data);
+ }
+ else if (method != null)
+ {
+ instance = method.IsStatic ? null : ProviderCache.GetInstanceOf(fixtureType);
+ foreach (object data in (IEnumerable)method.Invoke(instance, new Type[0]))
+ datapoints.Add(data);
+ }
+ }
+ }
+ }
+
+ if (datapoints.Count == 0)
+ {
+ if (parameterType == typeof(bool))
+ {
+ datapoints.Add(true);
+ datapoints.Add(false);
+ }
+ else if (parameterType.GetTypeInfo().IsEnum)
+ {
+ foreach (object o in TypeHelper.GetEnumValues(parameterType))
+ datapoints.Add(o);
+ }
+ }
+
+ return datapoints;
+ }
+
+ private Type GetTypeFromMemberInfo(MemberInfo member)
+ {
+ var field = member as FieldInfo;
+ if (field != null)
+ return field.FieldType;
+
+ var property = member as PropertyInfo;
+ if (property != null)
+ return property.PropertyType;
+
+ var method = member as MethodInfo;
+ if (method != null)
+ return method.ReturnType;
+
+ return null;
+ }
+
+ private Type GetElementTypeFromMemberInfo(MemberInfo member)
+ {
+ Type type = GetTypeFromMemberInfo(member);
+
+ if (type == null)
+ return null;
+
+ if (type.IsArray)
+ return type.GetElementType();
+
+ if (type.GetTypeInfo().IsGenericType && type.Name == "IEnumerable`1")
+ return type.GetGenericArguments()[0];
+
+ return null;
+ }
+
+ #endregion
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Builders
+{
+ /// <summary>
+ /// Built-in SuiteBuilder for all types of test classes.
+ /// </summary>
+ public class DefaultSuiteBuilder : ISuiteBuilder
+ {
+ // Builder we use for fixtures without any fixture attribute specified
+ private NUnitTestFixtureBuilder _defaultBuilder = new NUnitTestFixtureBuilder();
+
+ #region ISuiteBuilder Methods
+ /// <summary>
+ /// Checks to see if the provided Type is a fixture.
+ /// To be considered a fixture, it must be a non-abstract
+ /// class with one or more attributes implementing the
+ /// IFixtureBuilder interface or one or more methods
+ /// marked as tests.
+ /// </summary>
+ /// <param name="typeInfo">The fixture type to check</param>
+ /// <returns>True if the fixture can be built, false if not</returns>
+ public bool CanBuildFrom(ITypeInfo typeInfo)
+ {
+ if (typeInfo.IsAbstract && !typeInfo.IsSealed)
+ return false;
+
+ if (typeInfo.IsDefined<IFixtureBuilder>(true))
+ return true;
+
+ // Generics must have an attribute in order to provide
+ // them with arguments to determine the specific type.
+ // TODO: What about automatic fixtures? Should there
+ // be some kind of error shown?
+ if (typeInfo.IsGenericTypeDefinition)
+ return false;
+
+ return typeInfo.HasMethodWithAttribute(typeof(IImplyFixture));
+ }
+
+ /// <summary>
+ /// Build a TestSuite from TypeInfo provided.
+ /// </summary>
+ /// <param name="typeInfo">The fixture type to build</param>
+ /// <returns>A TestSuite built from that type</returns>
+ public TestSuite BuildFrom(ITypeInfo typeInfo)
+ {
+ var fixtures = new List<TestSuite>();
+
+ try
+ {
+ IFixtureBuilder[] builders = GetFixtureBuilderAttributes(typeInfo);
+
+ foreach (var builder in builders)
+ foreach (var fixture in builder.BuildFrom(typeInfo))
+ fixtures.Add(fixture);
+
+ if (typeInfo.IsGenericType)
+ return BuildMultipleFixtures(typeInfo, fixtures);
+
+ switch (fixtures.Count)
+ {
+ case 0:
+ return _defaultBuilder.BuildFrom(typeInfo);
+ case 1:
+ return fixtures[0];
+ default:
+ return BuildMultipleFixtures(typeInfo, fixtures);
+ }
+ }
+ catch (Exception ex)
+ {
+ var fixture = new TestFixture(typeInfo);
+ fixture.RunState = RunState.NotRunnable;
+
+ if (ex is System.Reflection.TargetInvocationException)
+ ex = ex.InnerException;
+ var msg = "An exception was thrown while loading the test." + Env.NewLine + ex.ToString();
+ fixture.Properties.Add(PropertyNames.SkipReason, msg);
+
+ return fixture;
+ }
+ }
+ #endregion
+
+ #region Helper Methods
+
+ private TestSuite BuildMultipleFixtures(ITypeInfo typeInfo, IEnumerable<TestSuite> fixtures)
+ {
+ TestSuite suite = new ParameterizedFixtureSuite(typeInfo);
+
+ foreach (var fixture in fixtures)
+ suite.Add(fixture);
+
+ return suite;
+ }
+
+ /// <summary>
+ /// We look for attributes implementing IFixtureBuilder at one level
+ /// of inheritance at a time. Attributes on base classes are not used
+ /// unless there are no fixture builder attributes at all on the derived
+ /// class. This is by design.
+ /// </summary>
+ /// <param name="typeInfo">The type being examined for attributes</param>
+ /// <returns>A list of the attributes found.</returns>
+ private IFixtureBuilder[] GetFixtureBuilderAttributes(ITypeInfo typeInfo)
+ {
+ IFixtureBuilder[] attrs = new IFixtureBuilder[0];
+
+ while (typeInfo != null && !typeInfo.IsType(typeof(object)))
+ {
+ attrs = (IFixtureBuilder[])typeInfo.GetCustomAttributes<IFixtureBuilder>(false);
+
+ if (attrs.Length > 0)
+ {
+ // We want to eliminate duplicates that have no args.
+ // If there is just one, no duplication is possible.
+ if (attrs.Length == 1)
+ return attrs;
+
+ // Count how many have arguments
+ int withArgs = 0;
+ foreach (var attr in attrs)
+ if (HasArguments(attr))
+ withArgs++;
+
+ // If all have args, just return them
+ if (withArgs == attrs.Length)
+ return attrs;
+
+ // If none of them have args, return the first one
+ if (withArgs == 0)
+ return new IFixtureBuilder[] { attrs[0] };
+
+ // Some of each - extract those with args
+ var result = new IFixtureBuilder[withArgs];
+ int count = 0;
+ foreach (var attr in attrs)
+ if (HasArguments(attr))
+ result[count++] = attr;
+
+ return result;
+ }
+
+ typeInfo = typeInfo.BaseType;
+ }
+
+ return attrs;
+ }
+
+ private bool HasArguments(IFixtureBuilder attr)
+ {
+ // Only TestFixtureAttribute can be used without arguments
+ var temp = attr as TestFixtureAttribute;
+
+ return temp == null || temp.Arguments.Length > 0 || temp.TypeArgs.Length > 0;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal.Commands;
+
+namespace NUnit.Framework.Internal.Builders
+{
+ /// <summary>
+ /// Class to build ether a parameterized or a normal NUnitTestMethod.
+ /// There are four cases that the builder must deal with:
+ /// 1. The method needs no params and none are provided
+ /// 2. The method needs params and they are provided
+ /// 3. The method needs no params but they are provided in error
+ /// 4. The method needs params but they are not provided
+ /// This could have been done using two different builders, but it
+ /// turned out to be simpler to have just one. The BuildFrom method
+ /// takes a different branch depending on whether any parameters are
+ /// provided, but all four cases are dealt with in lower-level methods
+ /// </summary>
+ public class DefaultTestCaseBuilder : ITestCaseBuilder
+ {
+ private NUnitTestCaseBuilder _nunitTestCaseBuilder = new NUnitTestCaseBuilder();
+
+ #region ITestCaseBuilder Methods
+ /// <summary>
+ /// Determines if the method can be used to build an NUnit test
+ /// test method of some kind. The method must normally be marked
+ /// with an identifying attribute for this to be true.
+ ///
+ /// Note that this method does not check that the signature
+ /// of the method for validity. If we did that here, any
+ /// test methods with invalid signatures would be passed
+ /// over in silence in the test run. Since we want such
+ /// methods to be reported, the check for validity is made
+ /// in BuildFrom rather than here.
+ /// </summary>
+ /// <param name="method">An IMethodInfo for the method being used as a test method</param>
+ /// <returns>True if the builder can create a test case from this method</returns>
+ public bool CanBuildFrom(IMethodInfo method)
+ {
+ return method.IsDefined<ITestBuilder>(false)
+ || method.IsDefined<ISimpleTestBuilder>(false);
+ }
+
+ /// <summary>
+ /// Build a Test from the provided MethodInfo. Depending on
+ /// whether the method takes arguments and on the availability
+ /// of test case data, this method may return a single test
+ /// or a group of tests contained in a ParameterizedMethodSuite.
+ /// </summary>
+ /// <param name="method">The method for which a test is to be built</param>
+ /// <returns>A Test representing one or more method invocations</returns>
+ public Test BuildFrom(IMethodInfo method)
+ {
+ return BuildFrom(method, null);
+ }
+
+ #endregion
+
+ #region ITestCaseBuilder2 Members
+
+ /// <summary>
+ /// Determines if the method can be used to build an NUnit test
+ /// test method of some kind. The method must normally be marked
+ /// with an identifying attribute for this to be true.
+ ///
+ /// Note that this method does not check that the signature
+ /// of the method for validity. If we did that here, any
+ /// test methods with invalid signatures would be passed
+ /// over in silence in the test run. Since we want such
+ /// methods to be reported, the check for validity is made
+ /// in BuildFrom rather than here.
+ /// </summary>
+ /// <param name="method">An IMethodInfo for the method being used as a test method</param>
+ /// <param name="parentSuite">The test suite being built, to which the new test would be added</param>
+ /// <returns>True if the builder can create a test case from this method</returns>
+ public bool CanBuildFrom(IMethodInfo method, Test parentSuite)
+ {
+ return CanBuildFrom(method);
+ }
+
+ /// <summary>
+ /// Build a Test from the provided MethodInfo. Depending on
+ /// whether the method takes arguments and on the availability
+ /// of test case data, this method may return a single test
+ /// or a group of tests contained in a ParameterizedMethodSuite.
+ /// </summary>
+ /// <param name="method">The method for which a test is to be built</param>
+ /// <param name="parentSuite">The test fixture being populated, or null</param>
+ /// <returns>A Test representing one or more method invocations</returns>
+ public Test BuildFrom(IMethodInfo method, Test parentSuite)
+ {
+ var tests = new List<TestMethod>();
+
+ List<ITestBuilder> builders = new List<ITestBuilder>(
+ (ITestBuilder[])method.GetCustomAttributes<ITestBuilder>(false));
+
+ // See if we need a CombinatorialAttribute added
+ bool needCombinatorial = true;
+ foreach (var attr in builders)
+ {
+ if (attr is CombiningStrategyAttribute)
+ needCombinatorial = false;
+ }
+
+ // We could check to see if here are any data attributes specified
+ // on the parameters but that's what CombinatorialAttribute does
+ // and it simply won't return any cases if it finds nothing.
+ // TODO: We need to add some other ITestBuilder than a combinatorial attribute
+ // because we want the attribute to generate an error if it's present on
+ // a generic method.
+ if (needCombinatorial)
+ builders.Add(new CombinatorialAttribute());
+
+ foreach (var attr in builders)
+ {
+ foreach (var test in attr.BuildFrom(method, parentSuite))
+ tests.Add(test);
+ }
+
+ return tests.Count > 0
+ ? BuildParameterizedMethodSuite(method, tests)
+ : BuildSingleTestMethod(method, parentSuite);
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ /// <summary>
+ /// Builds a ParameterizedMethodSuite containing individual test cases.
+ /// </summary>
+ /// <param name="method">The method for which a test is to be built.</param>
+ /// <param name="tests">The list of test cases to include.</param>
+ /// <returns>A ParameterizedMethodSuite populated with test cases</returns>
+ private Test BuildParameterizedMethodSuite(IMethodInfo method, IEnumerable<TestMethod> tests)
+ {
+ ParameterizedMethodSuite methodSuite = new ParameterizedMethodSuite(method);
+ methodSuite.ApplyAttributesToTest(method.MethodInfo);
+
+ foreach (TestMethod test in tests)
+ methodSuite.Add(test);
+
+ return methodSuite;
+ }
+
+ /// <summary>
+ /// Build a simple, non-parameterized TestMethod for this method.
+ /// </summary>
+ /// <param name="method">The MethodInfo for which a test is to be built</param>
+ /// <param name="suite">The test suite for which the method is being built</param>
+ /// <returns>A TestMethod.</returns>
+ private Test BuildSingleTestMethod(IMethodInfo method, Test suite)
+ {
+ var builders = (ISimpleTestBuilder[])method.GetCustomAttributes<ISimpleTestBuilder>(false);
+ return builders.Length > 0
+ ? builders[0].BuildFrom(method, suite)
+ : _nunitTestCaseBuilder.BuildTestMethod(method, suite, null);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+#if NETCF
+using System.Linq;
+#endif
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Builders
+{
+ /// <summary>
+ /// NUnitTestCaseBuilder is a utility class used by attributes
+ /// that build test cases.
+ /// </summary>
+ public class NUnitTestCaseBuilder
+ {
+ private readonly Randomizer _randomizer = Randomizer.CreateRandomizer();
+ private readonly TestNameGenerator _nameGenerator;
+
+ /// <summary>
+ /// Constructs an <see cref="NUnitTestCaseBuilder"/>
+ /// </summary>
+ public NUnitTestCaseBuilder()
+ {
+ _nameGenerator = new TestNameGenerator();
+ }
+
+ /// <summary>
+ /// Builds a single NUnitTestMethod, either as a child of the fixture
+ /// or as one of a set of test cases under a ParameterizedTestMethodSuite.
+ /// </summary>
+ /// <param name="method">The MethodInfo from which to construct the TestMethod</param>
+ /// <param name="parentSuite">The suite or fixture to which the new test will be added</param>
+ /// <param name="parms">The ParameterSet to be used, or null</param>
+ /// <returns></returns>
+ public TestMethod BuildTestMethod(IMethodInfo method, Test parentSuite, TestCaseParameters parms)
+ {
+ var testMethod = new TestMethod(method, parentSuite)
+ {
+ Seed = _randomizer.Next()
+ };
+
+ CheckTestMethodSignature(testMethod, parms);
+
+ if (parms == null || parms.Arguments == null)
+ testMethod.ApplyAttributesToTest(method.MethodInfo);
+
+ // NOTE: After the call to CheckTestMethodSignature, the Method
+ // property of testMethod may no longer be the same as the
+ // original MethodInfo, so we don't use it here.
+ string prefix = testMethod.Method.TypeInfo.FullName;
+
+ // Needed to give proper fullname to test in a parameterized fixture.
+ // Without this, the arguments to the fixture are not included.
+ if (parentSuite != null)
+ prefix = parentSuite.FullName;
+
+ if (parms != null)
+ {
+ parms.ApplyToTest(testMethod);
+
+ if (parms.TestName != null)
+ {
+ // The test is simply for efficiency
+ testMethod.Name = parms.TestName.Contains("{")
+ ? new TestNameGenerator(parms.TestName).GetDisplayName(testMethod, parms.OriginalArguments)
+ : parms.TestName;
+ }
+ else
+ {
+ testMethod.Name = _nameGenerator.GetDisplayName(testMethod, parms.OriginalArguments);
+ }
+ }
+ else
+ {
+ testMethod.Name = _nameGenerator.GetDisplayName(testMethod, null);
+ }
+
+ testMethod.FullName = prefix + "." + testMethod.Name;
+
+ return testMethod;
+ }
+
+ #region Helper Methods
+
+ /// <summary>
+ /// Helper method that checks the signature of a TestMethod and
+ /// any supplied parameters to determine if the test is valid.
+ ///
+ /// Currently, NUnitTestMethods are required to be public,
+ /// non-abstract methods, either static or instance,
+ /// returning void. They may take arguments but the _values must
+ /// be provided or the TestMethod is not considered runnable.
+ ///
+ /// Methods not meeting these criteria will be marked as
+ /// non-runnable and the method will return false in that case.
+ /// </summary>
+ /// <param name="testMethod">The TestMethod to be checked. If it
+ /// is found to be non-runnable, it will be modified.</param>
+ /// <param name="parms">Parameters to be used for this test, or null</param>
+ /// <returns>True if the method signature is valid, false if not</returns>
+ /// <remarks>
+ /// The return value is no longer used internally, but is retained
+ /// for testing purposes.
+ /// </remarks>
+ private static bool CheckTestMethodSignature(TestMethod testMethod, TestCaseParameters parms)
+ {
+ if (testMethod.Method.IsAbstract)
+ return MarkAsNotRunnable(testMethod, "Method is abstract");
+
+ if (!testMethod.Method.IsPublic)
+ return MarkAsNotRunnable(testMethod, "Method is not public");
+
+ IParameterInfo[] parameters;
+#if NETCF
+ if (testMethod.Method.IsGenericMethodDefinition)
+ {
+ if (parms != null && parms.Arguments != null)
+ {
+ var mi = testMethod.Method.MakeGenericMethodEx(parms.Arguments);
+ if (mi == null)
+ return MarkAsNotRunnable(testMethod, "Cannot determine generic types by probing");
+ testMethod.Method = mi;
+ parameters = testMethod.Method.GetParameters();
+ }
+ else
+ parameters = new IParameterInfo[0];
+ }
+ else
+ parameters = testMethod.Method.GetParameters();
+
+ int minArgsNeeded = parameters.Length;
+#else
+ parameters = testMethod.Method.GetParameters();
+ int minArgsNeeded = 0;
+ foreach (var parameter in parameters)
+ {
+ // IsOptional is supported since .NET 1.1
+ if (!parameter.IsOptional)
+ minArgsNeeded++;
+ }
+#endif
+ int maxArgsNeeded = parameters.Length;
+
+ object[] arglist = null;
+ int argsProvided = 0;
+
+ if (parms != null)
+ {
+ testMethod.parms = parms;
+ testMethod.RunState = parms.RunState;
+
+ arglist = parms.Arguments;
+
+ if (arglist != null)
+ argsProvided = arglist.Length;
+
+ if (testMethod.RunState != RunState.Runnable)
+ return false;
+ }
+
+#if NETCF
+ ITypeInfo returnType = testMethod.Method.IsGenericMethodDefinition && (parms == null || parms.Arguments == null) ? new TypeWrapper(typeof(void)) : testMethod.Method.ReturnType;
+#else
+ ITypeInfo returnType = testMethod.Method.ReturnType;
+#endif
+
+#if NET_4_0 || NET_4_5 || PORTABLE
+ if (AsyncInvocationRegion.IsAsyncOperation(testMethod.Method.MethodInfo))
+ {
+ if (returnType.IsType(typeof(void)))
+ return MarkAsNotRunnable(testMethod, "Async test method must have non-void return type");
+
+ var returnsGenericTask = returnType.IsGenericType &&
+ returnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>);
+
+ if (returnsGenericTask && (parms == null || !parms.HasExpectedResult))
+ return MarkAsNotRunnable(testMethod,
+ "Async test method must have non-generic Task return type when no result is expected");
+
+ if (!returnsGenericTask && parms != null && parms.HasExpectedResult)
+ return MarkAsNotRunnable(testMethod,
+ "Async test method must have Task<T> return type when a result is expected");
+ }
+ else
+#endif
+ if (returnType.IsType(typeof(void)))
+ {
+ if (parms != null && parms.HasExpectedResult)
+ return MarkAsNotRunnable(testMethod, "Method returning void cannot have an expected result");
+ }
+ else if (parms == null || !parms.HasExpectedResult)
+ return MarkAsNotRunnable(testMethod, "Method has non-void return value, but no result is expected");
+
+ if (argsProvided > 0 && maxArgsNeeded == 0)
+ return MarkAsNotRunnable(testMethod, "Arguments provided for method not taking any");
+
+ if (argsProvided == 0 && minArgsNeeded > 0)
+ return MarkAsNotRunnable(testMethod, "No arguments were provided");
+
+ if (argsProvided < minArgsNeeded)
+ return MarkAsNotRunnable(testMethod, string.Format("Not enough arguments provided, provide at least {0} arguments.", minArgsNeeded));
+
+ if (argsProvided > maxArgsNeeded)
+ return MarkAsNotRunnable(testMethod, string.Format("Too many arguments provided, provide at most {0} arguments.", maxArgsNeeded));
+
+ if (testMethod.Method.IsGenericMethodDefinition && arglist != null)
+ {
+ var typeArguments = new GenericMethodHelper(testMethod.Method.MethodInfo).GetTypeArguments(arglist);
+ foreach (Type o in typeArguments)
+ if (o == null || o == TypeHelper.NonmatchingType)
+ return MarkAsNotRunnable(testMethod, "Unable to determine type arguments for method");
+
+
+ testMethod.Method = testMethod.Method.MakeGenericMethod(typeArguments);
+ parameters = testMethod.Method.GetParameters();
+ }
+
+ if (arglist != null && parameters != null)
+ TypeHelper.ConvertArgumentList(arglist, parameters);
+
+ return true;
+ }
+
+ private static bool MarkAsNotRunnable(TestMethod testMethod, string reason)
+ {
+ testMethod.RunState = RunState.NotRunnable;
+ testMethod.Properties.Set(PropertyNames.SkipReason, reason);
+ return false;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Builders
+{
+ /// <summary>
+ /// NUnitTestFixtureBuilder is able to build a fixture given
+ /// a class marked with a TestFixtureAttribute or an unmarked
+ /// class containing test methods. In the first case, it is
+ /// called by the attribute and in the second directly by
+ /// NUnitSuiteBuilder.
+ /// </summary>
+ public class NUnitTestFixtureBuilder
+ {
+ #region Static Fields
+
+ static readonly string NO_TYPE_ARGS_MSG =
+ "Fixture type contains generic parameters. You must either provide " +
+ "Type arguments or specify constructor arguments that allow NUnit " +
+ "to deduce the Type arguments.";
+
+ #endregion
+
+ #region Instance Fields
+
+ private ITestCaseBuilder _testBuilder = new DefaultTestCaseBuilder();
+
+ #endregion
+
+ #region Public Methods
+
+ /// <summary>
+ /// Build a TestFixture from type provided. A non-null TestSuite
+ /// must always be returned, since the method is generally called
+ /// because the user has marked the target class as a fixture.
+ /// If something prevents the fixture from being used, it should
+ /// be returned nonetheless, labelled as non-runnable.
+ /// </summary>
+ /// <param name="typeInfo">An ITypeInfo for the fixture to be used.</param>
+ /// <returns>A TestSuite object or one derived from TestSuite.</returns>
+ // TODO: This should really return a TestFixture, but that requires changes to the Test hierarchy.
+ public TestSuite BuildFrom(ITypeInfo typeInfo)
+ {
+ var fixture = new TestFixture(typeInfo);
+
+ if (fixture.RunState != RunState.NotRunnable)
+ CheckTestFixtureIsValid(fixture);
+
+ fixture.ApplyAttributesToTest(typeInfo.Type.GetTypeInfo());
+
+ AddTestCasesToFixture(fixture);
+
+ return fixture;
+ }
+
+ /// <summary>
+ /// Overload of BuildFrom called by tests that have arguments.
+ /// Builds a fixture using the provided type and information
+ /// in the ITestFixtureData object.
+ /// </summary>
+ /// <param name="typeInfo">The TypeInfo for which to construct a fixture.</param>
+ /// <param name="testFixtureData">An object implementing ITestFixtureData or null.</param>
+ /// <returns></returns>
+ public TestSuite BuildFrom(ITypeInfo typeInfo, ITestFixtureData testFixtureData)
+ {
+ Guard.ArgumentNotNull(testFixtureData, "testFixtureData");
+
+ object[] arguments = testFixtureData.Arguments;
+
+ if (typeInfo.ContainsGenericParameters)
+ {
+ Type[] typeArgs = testFixtureData.TypeArgs;
+ if (typeArgs.Length == 0)
+ {
+ int cnt = 0;
+ foreach (object o in arguments)
+ if (o is Type) cnt++;
+ else break;
+
+ typeArgs = new Type[cnt];
+ for (int i = 0; i < cnt; i++)
+ typeArgs[i] = (Type)arguments[i];
+
+ if (cnt > 0)
+ {
+ object[] args = new object[arguments.Length - cnt];
+ for (int i = 0; i < args.Length; i++)
+ args[i] = arguments[cnt + i];
+
+ arguments = args;
+ }
+ }
+
+ if (typeArgs.Length > 0 ||
+ TypeHelper.CanDeduceTypeArgsFromArgs(typeInfo.Type, arguments, ref typeArgs))
+ {
+ typeInfo = typeInfo.MakeGenericType(typeArgs);
+ }
+ }
+
+ var fixture = new TestFixture(typeInfo);
+
+ if (arguments != null && arguments.Length > 0)
+ {
+ string name = fixture.Name = typeInfo.GetDisplayName(arguments);
+ string nspace = typeInfo.Namespace;
+ fixture.FullName = nspace != null && nspace != ""
+ ? nspace + "." + name
+ : name;
+ fixture.Arguments = arguments;
+ }
+
+ if (fixture.RunState != RunState.NotRunnable)
+ fixture.RunState = testFixtureData.RunState;
+
+ foreach (string key in testFixtureData.Properties.Keys)
+ foreach (object val in testFixtureData.Properties[key])
+ fixture.Properties.Add(key, val);
+
+ if (fixture.RunState != RunState.NotRunnable)
+ CheckTestFixtureIsValid(fixture);
+
+ fixture.ApplyAttributesToTest(typeInfo.Type.GetTypeInfo());
+
+ AddTestCasesToFixture(fixture);
+
+ return fixture;
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ /// <summary>
+ /// Method to add test cases to the newly constructed fixture.
+ /// </summary>
+ /// <param name="fixture">The fixture to which cases should be added</param>
+ private void AddTestCasesToFixture(TestFixture fixture)
+ {
+ // TODO: Check this logic added from Neil's build.
+ if (fixture.TypeInfo.ContainsGenericParameters)
+ {
+ fixture.RunState = RunState.NotRunnable;
+ fixture.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG);
+ return;
+ }
+
+ var methods = fixture.TypeInfo.GetMethods(
+ BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
+
+ foreach (IMethodInfo method in methods)
+ {
+ Test test = BuildTestCase(method, fixture);
+
+ if (test != null)
+ {
+ fixture.Add(test);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Method to create a test case from a MethodInfo and add
+ /// it to the fixture being built. It first checks to see if
+ /// any global TestCaseBuilder addin wants to build the
+ /// test case. If not, it uses the internal builder
+ /// collection maintained by this fixture builder.
+ ///
+ /// The default implementation has no test case builders.
+ /// Derived classes should add builders to the collection
+ /// in their constructor.
+ /// </summary>
+ /// <param name="method">The method for which a test is to be created</param>
+ /// <param name="suite">The test suite being built.</param>
+ /// <returns>A newly constructed Test</returns>
+ private Test BuildTestCase(IMethodInfo method, TestSuite suite)
+ {
+ return _testBuilder.CanBuildFrom(method, suite)
+ ? _testBuilder.BuildFrom(method, suite)
+ : null;
+ }
+
+ private static void CheckTestFixtureIsValid(TestFixture fixture)
+ {
+ if (fixture.TypeInfo.ContainsGenericParameters)
+ {
+ fixture.RunState = RunState.NotRunnable;
+ fixture.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG);
+ }
+ else if (!fixture.TypeInfo.IsStaticClass)
+ {
+ Type[] argTypes = Reflect.GetTypeArray(fixture.Arguments);
+
+ if (!fixture.TypeInfo.HasConstructor(argTypes))
+ {
+ fixture.RunState = RunState.NotRunnable;
+ fixture.Properties.Set(PropertyNames.SkipReason, "No suitable constructor was found");
+ }
+ }
+ }
+
+ private static bool IsStaticClass(Type type)
+ {
+ return type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections;
+using System.Collections.Generic;
+
+namespace NUnit.Framework.Internal.Builders
+{
+ /// <summary>
+ /// Class that can build a tree of automatic namespace
+ /// suites from a group of fixtures.
+ /// </summary>
+ public class NamespaceTreeBuilder
+ {
+ #region Instance Variables
+
+ /// <summary>
+ /// NamespaceDictionary of all test suites we have created to represent
+ /// namespaces. Used to locate namespace parent suites for fixtures.
+ /// </summary>
+ Dictionary<string, TestSuite> namespaceSuites = new Dictionary<string, TestSuite>();
+
+ /// <summary>
+ /// The root of the test suite being created by this builder.
+ /// </summary>
+ TestSuite rootSuite;
+
+ #endregion
+
+ #region Constructor
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NamespaceTreeBuilder"/> class.
+ /// </summary>
+ /// <param name="rootSuite">The root suite.</param>
+ public NamespaceTreeBuilder( TestSuite rootSuite )
+ {
+ this.rootSuite = rootSuite;
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Gets the root entry in the tree created by the NamespaceTreeBuilder.
+ /// </summary>
+ /// <value>The root suite.</value>
+ public TestSuite RootSuite
+ {
+ get { return rootSuite; }
+ }
+
+ #endregion
+
+ #region Public Methods
+
+ /// <summary>
+ /// Adds the specified fixtures to the tree.
+ /// </summary>
+ /// <param name="fixtures">The fixtures to be added.</param>
+ public void Add( IList<Test> fixtures )
+ {
+ foreach (TestSuite fixture in fixtures)
+ //if (fixture is SetUpFixture)
+ // Add(fixture as SetUpFixture);
+ //else
+ Add( fixture );
+ }
+
+ /// <summary>
+ /// Adds the specified fixture to the tree.
+ /// </summary>
+ /// <param name="fixture">The fixture to be added.</param>
+ public void Add( TestSuite fixture )
+ {
+ string ns = GetNamespaceForFixture(fixture);
+ TestSuite containingSuite = BuildFromNameSpace( ns );
+
+ if (fixture is SetUpFixture)
+ AddSetUpFixture(fixture, containingSuite, ns);
+ else
+ containingSuite.Add( fixture );
+ }
+
+ #endregion
+
+ #region Helper Method
+
+ private static string GetNamespaceForFixture(TestSuite fixture)
+ {
+ string ns = fixture.FullName;
+ int index = ns.IndexOfAny(new char[] { '[', '(' });
+ if (index >= 0) ns = ns.Substring(0, index);
+ index = ns.LastIndexOf('.');
+ ns = index > 0 ? ns.Substring(0, index) : string.Empty;
+ return ns;
+ }
+
+ private TestSuite BuildFromNameSpace( string ns )
+ {
+ if( ns == null || ns == "" ) return rootSuite;
+
+ TestSuite suite = namespaceSuites.ContainsKey(ns)
+ ? namespaceSuites[ns]
+ : null;
+
+ if (suite != null)
+ return suite;
+
+ int index = ns.LastIndexOf(".");
+ if( index == -1 )
+ {
+ suite = new TestSuite( ns );
+ if ( rootSuite == null )
+ rootSuite = suite;
+ else
+ rootSuite.Add(suite);
+ }
+ else
+ {
+ string parentNamespace = ns.Substring( 0,index );
+ TestSuite parent = BuildFromNameSpace( parentNamespace );
+ string suiteName = ns.Substring( index+1 );
+ suite = new TestSuite( parentNamespace, suiteName );
+ parent.Add( suite );
+ }
+
+ namespaceSuites[ns] = suite;
+ return suite;
+ }
+
+ private void AddSetUpFixture(TestSuite newSetupFixture, TestSuite containingSuite, string ns)
+ {
+ // The SetUpFixture must replace the namespace suite
+ // in which it is "contained".
+ //
+ // First, add the old suite's children
+ foreach (TestSuite child in containingSuite.Tests)
+ newSetupFixture.Add(child);
+
+ if (containingSuite is SetUpFixture)
+ {
+ // The parent suite is also a SetupFixture. The new
+ // SetupFixture is nested below the parent SetupFixture.
+ // TODO: Avoid nesting of SetupFixtures somehow?
+ //
+ // Note: The tests have already been copied to the new
+ // SetupFixture. Thus the tests collection of
+ // the parent SetupFixture can be cleared.
+ containingSuite.Tests.Clear();
+ containingSuite.Add(newSetupFixture);
+ }
+ else
+ {
+ // Make the parent of the containing suite point to this
+ // fixture instead
+ // TODO: Get rid of this somehow?
+ TestSuite parent = (TestSuite)containingSuite.Parent;
+ if (parent == null)
+ {
+ newSetupFixture.Name = rootSuite.Name;
+ rootSuite = newSetupFixture;
+ }
+ else
+ {
+ parent.Tests.Remove(containingSuite);
+ parent.Add(newSetupFixture);
+ }
+ }
+
+ // Update the dictionary
+ namespaceSuites[ns] = newSetupFixture;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Text;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Builders
+{
+ /// <summary>
+ /// PairwiseStrategy creates test cases by combining the parameter
+ /// data so that all possible pairs of data items are used.
+ /// </summary>
+ /// <remarks>
+ /// <para>
+ /// The number of test cases that cover all possible pairs of test function
+ /// parameters values is significantly less than the number of test cases
+ /// that cover all possible combination of test function parameters values.
+ /// And because different studies show that most of software failures are
+ /// caused by combination of no more than two parameters, pairwise testing
+ /// can be an effective ways to test the system when it's impossible to test
+ /// all combinations of parameters.
+ /// </para>
+ /// <para>
+ /// The PairwiseStrategy code is based on "jenny" tool by Bob Jenkins:
+ /// http://burtleburtle.net/bob/math/jenny.html
+ /// </para>
+ /// </remarks>
+ public class PairwiseStrategy : ICombiningStrategy
+ {
+ // NOTE: Terminology in this class is based on the literature
+ // relating to strategies for combining variable features when
+ // creating tests. This terminology is more closely related to
+ // higher level testing than it is to unit tests. See
+ // comments in the code for further explanations.
+
+ #region Internals
+
+ /// <summary>
+ /// FleaRand is a pseudo-random number generator developed by Bob Jenkins:
+ /// http://burtleburtle.net/bob/rand/talksmall.html#flea
+ /// </summary>
+ internal class FleaRand
+ {
+ private uint _b;
+ private uint _c;
+ private uint _d;
+ private uint _z;
+ private uint[] _m;
+ private uint[] _r;
+ private uint _q;
+
+ /// <summary>
+ /// Initializes a new instance of the FleaRand class.
+ /// </summary>
+ /// <param name="seed">The seed.</param>
+ public FleaRand( uint seed )
+ {
+ _b = seed;
+ _c = seed;
+ _d = seed;
+ _z = seed;
+ _m = new uint[256];
+ _r = new uint[256];
+
+ for ( int i = 0; i < _m.Length; i++ )
+ {
+ _m[i] = seed;
+ }
+
+ for ( int i = 0; i < 10; i++ )
+ {
+ Batch();
+ }
+
+ _q = 0;
+ }
+
+ public uint Next()
+ {
+ if ( _q == 0 )
+ {
+ Batch();
+ _q = (uint)_r.Length - 1;
+ }
+ else
+ {
+ _q--;
+ }
+
+ return _r[_q];
+ }
+
+ private void Batch()
+ {
+ uint a;
+ uint b = _b;
+ uint c = _c + ( ++_z );
+ uint d = _d;
+
+ for ( int i = 0; i < _r.Length; i++ )
+ {
+ a = _m[b % _m.Length];
+ _m[b % _m.Length] = d;
+ d = ( c << 19 ) + ( c >> 13 ) + b;
+ c = b ^ _m[i];
+ b = a + d;
+ _r[i] = c;
+ }
+
+ _b = b;
+ _c = c;
+ _d = d;
+ }
+ }
+
+ /// <summary>
+ /// FeatureInfo represents coverage of a single value of test function
+ /// parameter, represented as a pair of indices, Dimension and Feature. In
+ /// terms of unit testing, Dimension is the index of the test parameter and
+ /// Feature is the index of the supplied value in that parameter's list of
+ /// sources.
+ /// </summary>
+ internal class FeatureInfo
+ {
+ public readonly int Dimension;
+
+ public readonly int Feature;
+
+ /// <summary>
+ /// Initializes a new instance of FeatureInfo class.
+ /// </summary>
+ /// <param name="dimension">Index of a dimension.</param>
+ /// <param name="feature">Index of a feature.</param>
+ public FeatureInfo( int dimension, int feature )
+ {
+ Dimension = dimension;
+ Feature = feature;
+ }
+ }
+
+ /// <summary>
+ /// A FeatureTuple represents a combination of features, one per test
+ /// parameter, which should be covered by a test case. In the
+ /// PairwiseStrategy, we are only trying to cover pairs of features, so the
+ /// tuples actually may contain only single feature or pair of features, but
+ /// the algorithm itself works with triplets, quadruples and so on.
+ /// </summary>
+ internal class FeatureTuple
+ {
+ private readonly FeatureInfo[] _features;
+
+ /// <summary>
+ /// Initializes a new instance of FeatureTuple class for a single feature.
+ /// </summary>
+ /// <param name="feature1">Single feature.</param>
+ public FeatureTuple( FeatureInfo feature1 )
+ {
+ _features = new FeatureInfo[] { feature1 };
+ }
+
+ /// <summary>
+ /// Initializes a new instance of FeatureTuple class for a pair of features.
+ /// </summary>
+ /// <param name="feature1">First feature.</param>
+ /// <param name="feature2">Second feature.</param>
+ public FeatureTuple( FeatureInfo feature1, FeatureInfo feature2 )
+ {
+ _features = new FeatureInfo[] { feature1, feature2 };
+ }
+
+ public int Length
+ {
+ get
+ {
+ return _features.Length;
+ }
+ }
+
+ public FeatureInfo this[int index]
+ {
+ get
+ {
+ return _features[index];
+ }
+ }
+ }
+
+ /// <summary>
+ /// TestCase represents a single test case covering a list of features.
+ /// </summary>
+ internal class TestCaseInfo
+ {
+ public readonly int[] Features;
+
+ /// <summary>
+ /// Initializes a new instance of TestCaseInfo class.
+ /// </summary>
+ /// <param name="length">A number of features in the test case.</param>
+ public TestCaseInfo( int length )
+ {
+ Features = new int[length];
+ }
+
+ public bool IsTupleCovered( FeatureTuple tuple )
+ {
+ for ( int i = 0; i < tuple.Length; i++ )
+ {
+ if ( Features[tuple[i].Dimension] != tuple[i].Feature )
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ }
+
+ /// <summary>
+ /// PairwiseTestCaseGenerator class implements an algorithm which generates
+ /// a set of test cases which covers all pairs of possible values of test
+ /// function.
+ /// </summary>
+ /// <remarks>
+ /// <para>
+ /// The algorithm starts with creating a set of all feature tuples which we
+ /// will try to cover (see <see
+ /// cref="PairwiseTestCaseGenerator.CreateAllTuples" /> method). This set
+ /// includes every single feature and all possible pairs of features. We
+ /// store feature tuples in the 3-D collection (where axes are "dimension",
+ /// "feature", and "all combinations which includes this feature"), and for
+ /// every two feature (e.g. "A" and "B") we generate both ("A", "B") and
+ /// ("B", "A") pairs. This data structure extremely reduces the amount of
+ /// time needed to calculate coverage for a single test case (this
+ /// calculation is the most time-consuming part of the algorithm).
+ /// </para>
+ /// <para>
+ /// Then the algorithm picks one tuple from the uncovered tuple, creates a
+ /// test case that covers this tuple, and then removes this tuple and all
+ /// other tuples covered by this test case from the collection of uncovered
+ /// tuples.
+ /// </para>
+ /// <para>
+ /// Picking a tuple to cover
+ /// </para>
+ /// <para>
+ /// There are no any special rules defined for picking tuples to cover. We
+ /// just pick them one by one, in the order they were generated.
+ /// </para>
+ /// <para>
+ /// Test generation
+ /// </para>
+ /// <para>
+ /// Test generation starts from creating a completely random test case which
+ /// covers, nevertheless, previously selected tuple. Then the algorithm
+ /// tries to maximize number of tuples which this test covers.
+ /// </para>
+ /// <para>
+ /// Test generation and maximization process repeats seven times for every
+ /// selected tuple and then the algorithm picks the best test case ("seven"
+ /// is a magic number which provides good results in acceptable time).
+ /// </para>
+ /// <para>Maximizing test coverage</para>
+ /// <para>
+ /// To maximize tests coverage, the algorithm walks thru the list of mutable
+ /// dimensions (mutable dimension is a dimension that are not included in
+ /// the previously selected tuple). Then for every dimension, the algorithm
+ /// walks thru the list of features and checks if this feature provides
+ /// better coverage than randomly selected feature, and if yes keeps this
+ /// feature.
+ /// </para>
+ /// <para>
+ /// This process repeats while it shows progress. If the last iteration
+ /// doesn't improve coverage, the process ends.
+ /// </para>
+ /// <para>
+ /// In addition, for better results, before start every iteration, the
+ /// algorithm "scrambles" dimensions - so for every iteration dimension
+ /// probes in a different order.
+ /// </para>
+ /// </remarks>
+ internal class PairwiseTestCaseGenerator
+ {
+ private FleaRand _prng;
+
+ private int[] _dimensions;
+
+ private List<FeatureTuple>[][] _uncoveredTuples;
+
+ /// <summary>
+ /// Creates a set of test cases for specified dimensions.
+ /// </summary>
+ /// <param name="dimensions">
+ /// An array which contains information about dimensions. Each element of
+ /// this array represents a number of features in the specific dimension.
+ /// </param>
+ /// <returns>
+ /// A set of test cases.
+ /// </returns>
+ public IEnumerable GetTestCases( int[] dimensions )
+ {
+ _prng = new FleaRand( 15485863 );
+ _dimensions = dimensions;
+
+ CreateAllTuples();
+
+ List<TestCaseInfo> testCases = new List<TestCaseInfo>();
+
+ while ( true )
+ {
+ FeatureTuple tuple = GetNextTuple();
+
+ if ( tuple == null )
+ {
+ break;
+ }
+
+ TestCaseInfo testCase = CreateTestCase( tuple );
+
+ RemoveTuplesCoveredByTest( testCase );
+
+ testCases.Add( testCase );
+ }
+
+#if DEBUG
+ SelfTest( testCases );
+#endif
+
+ return testCases;
+ }
+
+ private int GetNextRandomNumber()
+ {
+ return (int)( _prng.Next() >> 1 );
+ }
+
+ private void CreateAllTuples()
+ {
+ _uncoveredTuples = new List<FeatureTuple>[_dimensions.Length][];
+
+ for ( int d = 0; d < _dimensions.Length; d++ )
+ {
+ _uncoveredTuples[d] = new List<FeatureTuple>[_dimensions[d]];
+
+ for ( int f = 0; f < _dimensions[d]; f++ )
+ {
+ _uncoveredTuples[d][f] = CreateTuples( d, f );
+ }
+ }
+ }
+
+ private List<FeatureTuple> CreateTuples( int dimension, int feature )
+ {
+ List<FeatureTuple> result = new List<FeatureTuple>();
+
+ result.Add( new FeatureTuple( new FeatureInfo( dimension, feature ) ) );
+
+ for ( int d = 0; d < _dimensions.Length; d++ )
+ {
+ if ( d != dimension )
+ {
+ for ( int f = 0; f < _dimensions[d]; f++ )
+ {
+ result.Add( new FeatureTuple( new FeatureInfo( dimension, feature ), new FeatureInfo( d, f ) ) );
+ }
+ }
+ }
+
+ return result;
+ }
+
+ private FeatureTuple GetNextTuple()
+ {
+ for ( int d = 0; d < _uncoveredTuples.Length; d++ )
+ {
+ for ( int f = 0; f < _uncoveredTuples[d].Length; f++ )
+ {
+ List<FeatureTuple> tuples = _uncoveredTuples[d][f];
+
+ if ( tuples.Count > 0 )
+ {
+ FeatureTuple tuple = tuples[0];
+ tuples.RemoveAt( 0 );
+ return tuple;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private TestCaseInfo CreateTestCase( FeatureTuple tuple )
+ {
+ TestCaseInfo bestTestCase = null;
+ int bestCoverage = -1;
+
+ for ( int i = 0; i < 7; i++ )
+ {
+ TestCaseInfo testCase = CreateRandomTestCase( tuple );
+
+ int coverage = MaximizeCoverage( testCase, tuple );
+
+ if ( coverage > bestCoverage )
+ {
+ bestTestCase = testCase;
+ bestCoverage = coverage;
+ }
+ }
+
+ return bestTestCase;
+ }
+
+ private TestCaseInfo CreateRandomTestCase( FeatureTuple tuple )
+ {
+ TestCaseInfo result = new TestCaseInfo( _dimensions.Length );
+
+ for ( int d = 0; d < _dimensions.Length; d++ )
+ {
+ result.Features[d] = GetNextRandomNumber() % _dimensions[d];
+ }
+
+ for ( int i = 0; i < tuple.Length; i++ )
+ {
+ result.Features[tuple[i].Dimension] = tuple[i].Feature;
+ }
+
+ return result;
+ }
+
+ private int MaximizeCoverage( TestCaseInfo testCase, FeatureTuple tuple )
+ {
+ // It starts with one because we always have one tuple which is covered by the test.
+ int totalCoverage = 1;
+ int[] mutableDimensions = GetMutableDimensions( tuple );
+
+ while ( true )
+ {
+ bool progress = false;
+
+ ScrambleDimensions( mutableDimensions );
+
+ for ( int i = 0; i < mutableDimensions.Length; i++ )
+ {
+ int d = mutableDimensions[i];
+
+ int bestCoverage = CountTuplesCoveredByTest( testCase, d, testCase.Features[d] );
+
+ int newCoverage = MaximizeCoverageForDimension( testCase, d, bestCoverage );
+
+ totalCoverage += newCoverage;
+
+ if ( newCoverage > bestCoverage )
+ {
+ progress = true;
+ }
+ }
+
+ if ( !progress )
+ {
+ return totalCoverage;
+ }
+ }
+ }
+
+ private int[] GetMutableDimensions( FeatureTuple tuple )
+ {
+ List<int> result = new List<int>();
+
+ bool[] immutableDimensions = new bool[_dimensions.Length];
+
+ for ( int i = 0; i < tuple.Length; i++ )
+ {
+ immutableDimensions[tuple[i].Dimension] = true;
+ }
+
+ for ( int d = 0; d < _dimensions.Length; d++ )
+ {
+ if ( !immutableDimensions[d] )
+ {
+ result.Add( d );
+ }
+ }
+
+ return result.ToArray();
+ }
+
+ private void ScrambleDimensions( int[] dimensions )
+ {
+ for ( int i = 0; i < dimensions.Length; i++ )
+ {
+ int j = GetNextRandomNumber() % dimensions.Length;
+ int t = dimensions[i];
+ dimensions[i] = dimensions[j];
+ dimensions[j] = t;
+ }
+ }
+
+ private int MaximizeCoverageForDimension( TestCaseInfo testCase, int dimension, int bestCoverage )
+ {
+ List<int> bestFeatures = new List<int>( _dimensions[dimension] );
+
+ for ( int f = 0; f < _dimensions[dimension]; f++ )
+ {
+ testCase.Features[dimension] = f;
+
+ int coverage = CountTuplesCoveredByTest( testCase, dimension, f );
+
+ if ( coverage >= bestCoverage )
+ {
+ if ( coverage > bestCoverage )
+ {
+ bestCoverage = coverage;
+ bestFeatures.Clear();
+ }
+
+ bestFeatures.Add( f );
+ }
+ }
+
+ testCase.Features[dimension] = bestFeatures[GetNextRandomNumber() % bestFeatures.Count];
+
+ return bestCoverage;
+ }
+
+ private int CountTuplesCoveredByTest( TestCaseInfo testCase, int dimension, int feature )
+ {
+ int result = 0;
+
+ List<FeatureTuple> tuples = _uncoveredTuples[dimension][feature];
+
+ for ( int i = 0; i < tuples.Count; i++ )
+ {
+ if ( testCase.IsTupleCovered( tuples[i] ) )
+ {
+ result++;
+ }
+ }
+
+ return result;
+ }
+
+ private void RemoveTuplesCoveredByTest( TestCaseInfo testCase )
+ {
+ for ( int d = 0; d < _uncoveredTuples.Length; d++ )
+ {
+ for ( int f = 0; f < _uncoveredTuples[d].Length; f++ )
+ {
+ List<FeatureTuple> tuples = _uncoveredTuples[d][f];
+
+ for ( int i = tuples.Count - 1; i >= 0; i-- )
+ {
+ if ( testCase.IsTupleCovered( tuples[i] ) )
+ {
+ tuples.RemoveAt( i );
+ }
+ }
+ }
+ }
+ }
+
+#if DEBUG
+ private void SelfTest( List<TestCaseInfo> testCases )
+ {
+ for ( int d1 = 0; d1 < _dimensions.Length - 1; d1++ )
+ {
+ for ( int d2 = d1 + 1; d2 < _dimensions.Length; d2++ )
+ {
+ for ( int f1 = 0; f1 < _dimensions[d1]; f1++ )
+ {
+ for ( int f2 = 0; f2 < _dimensions[d2]; f2++ )
+ {
+ FeatureTuple tuple = new FeatureTuple( new FeatureInfo( d1, f1 ), new FeatureInfo( d2, f2 ) );
+
+ if ( !IsTupleCovered( testCases, tuple ) )
+ {
+ throw new InvalidOperationException( string.Format( "PairwiseStrategy : Not all pairs are covered : {0}", tuple.ToString() ) );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private bool IsTupleCovered( List<TestCaseInfo> testCases, FeatureTuple tuple )
+ {
+ foreach ( TestCaseInfo testCase in testCases )
+ {
+ if ( testCase.IsTupleCovered( tuple ) )
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+#endif
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets the test cases generated by this strategy instance.
+ /// </summary>
+ /// <returns>A set of test cases.</returns>
+ public IEnumerable<ITestCaseData> GetTestCases(IEnumerable[] sources)
+ {
+ List<ITestCaseData> testCases = new List<ITestCaseData>();
+ List<object>[] valueSet = CreateValueSet(sources);
+ int[] dimensions = CreateDimensions(valueSet);
+
+ IEnumerable pairwiseTestCases = new PairwiseTestCaseGenerator().GetTestCases( dimensions );
+
+ foreach (TestCaseInfo pairwiseTestCase in pairwiseTestCases)
+ {
+ object[] testData = new object[pairwiseTestCase.Features.Length];
+
+ for (int i = 0; i < pairwiseTestCase.Features.Length; i++)
+ {
+ testData[i] = valueSet[i][pairwiseTestCase.Features[i]];
+ }
+
+ TestCaseParameters parms = new TestCaseParameters(testData);
+ testCases.Add(parms);
+ }
+
+ return testCases;
+ }
+
+ private List<object>[] CreateValueSet(IEnumerable[] sources)
+ {
+ var valueSet = new List<object>[sources.Length];
+
+ for (int i = 0; i < valueSet.Length; i++)
+ {
+ var values = new List<object>();
+
+ foreach (object value in sources[i])
+ {
+ values.Add(value);
+ }
+
+ valueSet[i] = values;
+ }
+
+ return valueSet;
+ }
+
+ private int[] CreateDimensions(List<object>[] valueSet)
+ {
+ int[] dimensions = new int[valueSet.Length];
+
+ for (int i = 0; i < valueSet.Length; i++)
+ {
+ dimensions[i] = valueSet[i].Count;
+ }
+
+ return dimensions;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Text;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Builders
+{
+ /// <summary>
+ /// The ParameterDataProvider class implements IParameterDataProvider
+ /// and hosts one or more individual providers.
+ /// </summary>
+ public class ParameterDataProvider : IParameterDataProvider
+ {
+ private List<IParameterDataProvider> _providers = new List<IParameterDataProvider>();
+
+ /// <summary>
+ /// Construct with a collection of individual providers
+ /// </summary>
+ public ParameterDataProvider(params IParameterDataProvider[] providers)
+ {
+ _providers.AddRange(providers);
+ }
+
+ /// <summary>
+ /// Determine whether any data is available for a parameter.
+ /// </summary>
+ /// <param name="parameter">An IParameterInfo representing one
+ /// argument to a parameterized test</param>
+ /// <returns>True if any data is available, otherwise false.</returns>
+ public bool HasDataFor(IParameterInfo parameter)
+ {
+ foreach (var provider in _providers)
+ if (provider.HasDataFor(parameter))
+ return true;
+
+ return false;
+ }
+
+ /// <summary>
+ /// Return an IEnumerable providing data for use with the
+ /// supplied parameter.
+ /// </summary>
+ /// <param name="parameter">An IParameterInfo representing one
+ /// argument to a parameterized test</param>
+ /// <returns>An IEnumerable providing the required data</returns>
+ public IEnumerable GetDataFor(IParameterInfo parameter)
+ {
+ foreach (var provider in _providers)
+ foreach (object data in provider.GetDataFor(parameter))
+ yield return data;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Builders
+{
+ /// <summary>
+ /// ParameterDataSourceProvider supplies individual argument _values for
+ /// single parameters using attributes implementing IParameterDataSource.
+ /// </summary>
+ public class ParameterDataSourceProvider : IParameterDataProvider
+ {
+ #region IParameterDataProvider Members
+
+ /// <summary>
+ /// Determine whether any data is available for a parameter.
+ /// </summary>
+ /// <param name="parameter">A ParameterInfo representing one
+ /// argument to a parameterized test</param>
+ /// <returns>
+ /// True if any data is available, otherwise false.
+ /// </returns>
+ public bool HasDataFor(IParameterInfo parameter)
+ {
+ return parameter.IsDefined<IParameterDataSource>(false);
+ }
+
+ /// <summary>
+ /// Return an IEnumerable providing data for use with the
+ /// supplied parameter.
+ /// </summary>
+ /// <param name="parameter">An IParameterInfo representing one
+ /// argument to a parameterized test</param>
+ /// <returns>
+ /// An IEnumerable providing the required data
+ /// </returns>
+ public IEnumerable GetDataFor(IParameterInfo parameter)
+ {
+ var data = new List<object>();
+
+ foreach (IParameterDataSource source in parameter.GetCustomAttributes<IParameterDataSource>(false))
+ {
+ foreach (object item in source.GetData(parameter))
+ data.Add(item);
+ }
+
+ return data;
+ }
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Text;
+
+namespace NUnit.Framework.Internal.Builders
+{
+ class ProviderCache
+ {
+ private static Dictionary<CacheEntry, object> instances = new Dictionary<CacheEntry, object>();
+
+ public static object GetInstanceOf(Type providerType)
+ {
+ return GetInstanceOf(providerType, null);
+ }
+
+ public static object GetInstanceOf(Type providerType, object[] providerArgs)
+ {
+ CacheEntry entry = new CacheEntry(providerType, providerArgs);
+
+ object instance = instances.ContainsKey(entry)
+ ?instances[entry]
+ : null;
+
+ if (instance == null)
+ instances[entry] = instance = Reflect.Construct(providerType, providerArgs);
+
+ return instance;
+ }
+
+ public static void Clear()
+ {
+ foreach (CacheEntry key in instances.Keys)
+ {
+ IDisposable provider = instances[key] as IDisposable;
+ if (provider != null)
+ provider.Dispose();
+ }
+
+ instances.Clear();
+ }
+
+ class CacheEntry
+ {
+ private Type providerType;
+
+ public CacheEntry(Type providerType, object[] providerArgs)
+ {
+ this.providerType = providerType;
+ }
+
+ public override bool Equals(object obj)
+ {
+ CacheEntry other = obj as CacheEntry;
+ if (other == null) return false;
+
+ return this.providerType == other.providerType;
+ }
+
+ public override int GetHashCode()
+ {
+ return providerType.GetHashCode();
+ }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Builders
+{
+ /// <summary>
+ /// SequentialStrategy creates test cases by using all of the
+ /// parameter data sources in parallel, substituting <c>null</c>
+ /// when any of them run out of data.
+ /// </summary>
+ public class SequentialStrategy : ICombiningStrategy
+ {
+ /// <summary>
+ /// Gets the test cases generated by the CombiningStrategy.
+ /// </summary>
+ /// <returns>The test cases.</returns>
+ public IEnumerable<ITestCaseData> GetTestCases(IEnumerable[] sources)
+ {
+ List<ITestCaseData> testCases = new List<ITestCaseData>();
+
+ IEnumerator[] enumerators = new IEnumerator[sources.Length];
+ for (int i = 0; i < sources.Length; i++)
+ enumerators[i] = sources[i].GetEnumerator();
+
+ for (; ; )
+ {
+ bool gotData = false;
+ object[] testdata = new object[sources.Length];
+
+ for (int i = 0; i < sources.Length; i++)
+ if (enumerators[i].MoveNext())
+ {
+ testdata[i] = enumerators[i].Current;
+ gotData = true;
+ }
+ else
+ testdata[i] = null;
+
+ if (!gotData)
+ break;
+
+ TestCaseParameters parms = new TestCaseParameters(testdata);
+ testCases.Add(parms);
+ }
+
+ return testCases;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Commands
+{
+ /// <summary>
+ /// ContextSettingsCommand applies specified changes to the
+ /// TestExecutionContext prior to running a test. No special
+ /// action is needed after the test runs, since the prior
+ /// context will be restored automatically.
+ /// </summary>
+ class ApplyChangesToContextCommand : DelegatingTestCommand
+ {
+ private IEnumerable<IApplyToContext> _changes;
+
+ public ApplyChangesToContextCommand(TestCommand innerCommand, IEnumerable<IApplyToContext> changes)
+ : base(innerCommand)
+ {
+ _changes = changes;
+ }
+
+ public override TestResult Execute(TestExecutionContext context)
+ {
+ try
+ {
+ foreach (IApplyToContext change in _changes)
+ change.ApplyToContext(context);
+
+ context.CurrentResult = innerCommand.Execute(context);
+ }
+ catch (Exception ex)
+ {
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ if (ex is ThreadAbortException)
+ Thread.ResetAbort();
+#endif
+ context.CurrentResult.RecordException(ex);
+ }
+
+ return context.CurrentResult;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Internal.Commands
+{
+ /// <summary>
+ /// The CommandStage enumeration represents the defined stages
+ /// of execution for a series of TestCommands. The int _values
+ /// of the enum are used to apply decorators in the proper
+ /// order. Lower _values are applied first and are therefore
+ /// "closer" to the actual test execution.
+ /// </summary>
+ /// <remarks>
+ /// No CommandStage is defined for actual invocation of the test or
+ /// for creation of the context. Execution may be imagined as
+ /// proceeding from the bottom of the list upwards, with cleanup
+ /// after the test running in the opposite order.
+ /// </remarks>
+ public enum CommandStage
+ {
+ /// <summary>
+ /// Use an application-defined default value.
+ /// </summary>
+ Default,
+
+ // NOTE: The test is actually invoked here.
+
+ /// <summary>
+ /// Make adjustments needed before and after running
+ /// the raw test - that is, after any SetUp has run
+ /// and before TearDown.
+ /// </summary>
+ BelowSetUpTearDown,
+
+ /// <summary>
+ /// Run SetUp and TearDown for the test. This stage is used
+ /// internally by NUnit and should not normally appear
+ /// in user-defined decorators.
+ /// </summary>
+ SetUpTearDown,
+
+ /// <summary>
+ /// Make adjustments needed before and after running
+ /// the entire test - including SetUp and TearDown.
+ /// </summary>
+ AboveSetUpTearDown
+
+ // Note: The context is created here and destroyed
+ // after the test has run.
+
+ // Command Stages
+ // Create/Destroy Context
+ // Modify/Restore Context
+ // Create/Destroy fixture object
+ // Repeat test
+ // Create/Destroy thread
+ // Modify overall result
+ // SetUp/TearDown
+ // Modify raw result
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Commands
+{
+ /// <summary>
+ /// TODO: Documentation needed for class
+ /// </summary>
+ public abstract class DelegatingTestCommand : TestCommand
+ {
+ /// <summary>TODO: Documentation needed for field</summary>
+ protected TestCommand innerCommand;
+
+ /// <summary>
+ /// TODO: Documentation needed for constructor
+ /// </summary>
+ /// <param name="innerCommand"></param>
+ protected DelegatingTestCommand(TestCommand innerCommand)
+ : base(innerCommand.Test)
+ {
+ this.innerCommand = innerCommand;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Diagnostics;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Commands
+{
+ /// <summary>
+ /// TODO: Documentation needed for class
+ /// </summary>
+ public class MaxTimeCommand : DelegatingTestCommand
+ {
+ private int maxTime;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MaxTimeCommand"/> class.
+ /// </summary>
+ /// <param name="innerCommand">The inner command.</param>
+ /// <param name="maxTime">The max time allowed in milliseconds</param>
+ public MaxTimeCommand(TestCommand innerCommand, int maxTime)
+ : base(innerCommand)
+ {
+ this.maxTime = maxTime;
+ }
+
+ /// <summary>
+ /// Runs the test, saving a TestResult in the supplied TestExecutionContext
+ /// </summary>
+ /// <param name="context">The context in which the test should run.</param>
+ /// <returns>A TestResult</returns>
+ public override TestResult Execute(TestExecutionContext context)
+ {
+ // TODO: This command duplicates the calculation of the
+ // duration of the test because that calculation is
+ // normally performed at a higher level. Most likely,
+ // we should move the maxtime calculation to the
+ // higher level eventually.
+ long startTicks = Stopwatch.GetTimestamp();
+
+ TestResult testResult = innerCommand.Execute(context);
+
+ long tickCount = Stopwatch.GetTimestamp() - startTicks;
+ double seconds = (double)tickCount / Stopwatch.Frequency;
+ testResult.Duration = seconds;
+
+ if (testResult.ResultState == ResultState.Success)
+ {
+ double elapsedTime = testResult.Duration * 1000d;
+
+ if (elapsedTime > maxTime)
+ testResult.SetResult(ResultState.Failure,
+ string.Format("Elapsed time of {0}ms exceeds maximum of {1}ms",
+ elapsedTime, maxTime));
+ }
+
+ return testResult;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Commands
+{
+ /// <summary>
+ /// OneTimeSetUpCommand runs any one-time setup methods for a suite,
+ /// constructing the user test object if necessary.
+ /// </summary>
+ public class OneTimeSetUpCommand : TestCommand
+ {
+ private readonly TestSuite _suite;
+ private readonly ITypeInfo _typeInfo;
+ private readonly object[] _arguments;
+ private readonly List<SetUpTearDownItem> _setUpTearDown;
+ private readonly List<TestActionItem> _actions;
+
+ /// <summary>
+ /// Constructs a OneTimeSetUpCommand for a suite
+ /// </summary>
+ /// <param name="suite">The suite to which the command applies</param>
+ /// <param name="setUpTearDown">A SetUpTearDownList for use by the command</param>
+ /// <param name="actions">A List of TestActionItems to be run after Setup</param>
+ public OneTimeSetUpCommand(TestSuite suite, List<SetUpTearDownItem> setUpTearDown, List<TestActionItem> actions)
+ : base(suite)
+ {
+ _suite = suite;
+ _typeInfo = suite.TypeInfo;
+ _arguments = suite.Arguments;
+ _setUpTearDown = setUpTearDown;
+ _actions = actions;
+ }
+
+ /// <summary>
+ /// Overridden to run the one-time setup for a suite.
+ /// </summary>
+ /// <param name="context">The TestExecutionContext to be used.</param>
+ /// <returns>A TestResult</returns>
+ public override TestResult Execute(TestExecutionContext context)
+ {
+ if (_typeInfo != null)
+ {
+ // Use pre-constructed fixture if available, otherwise construct it
+ if (!_typeInfo.IsStaticClass)
+ {
+ context.TestObject = _suite.Fixture ?? _typeInfo.Construct(_arguments);
+ if (_suite.Fixture == null)
+ {
+ _suite.Fixture = context.TestObject;
+ }
+ Test.Fixture = _suite.Fixture;
+ }
+
+ for (int i = _setUpTearDown.Count; i > 0; )
+ _setUpTearDown[--i].RunSetUp(context);
+ }
+
+
+ for (int i = 0; i < _actions.Count; i++)
+ _actions[i].BeforeTest(Test);
+
+ return context.CurrentResult;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Commands
+{
+ /// <summary>
+ /// OneTimeTearDownCommand performs any teardown actions
+ /// specified for a suite and calls Dispose on the user
+ /// test object, if any.
+ /// </summary>
+ public class OneTimeTearDownCommand : TestCommand
+ {
+ private List<SetUpTearDownItem> _setUpTearDownItems;
+ private List<TestActionItem> _actions;
+
+ /// <summary>
+ /// Construct a OneTimeTearDownCommand
+ /// </summary>
+ /// <param name="suite">The test suite to which the command applies</param>
+ /// <param name="setUpTearDownItems">A SetUpTearDownList for use by the command</param>
+ /// <param name="actions">A List of TestActionItems to be run before teardown.</param>
+ public OneTimeTearDownCommand(TestSuite suite, List<SetUpTearDownItem> setUpTearDownItems, List<TestActionItem> actions)
+ : base(suite)
+ {
+ _setUpTearDownItems = setUpTearDownItems;
+ _actions = actions;
+ }
+
+ /// <summary>
+ /// Overridden to run the teardown methods specified on the test.
+ /// </summary>
+ /// <param name="context">The TestExecutionContext to be used.</param>
+ /// <returns>A TestResult</returns>
+ public override TestResult Execute(TestExecutionContext context)
+ {
+ TestResult suiteResult = context.CurrentResult;
+
+ try
+ {
+ for (int i = _actions.Count; i > 0; )
+ _actions[--i].AfterTest(Test);
+
+ if (_setUpTearDownItems != null)
+ foreach(var item in _setUpTearDownItems)
+ item.RunTearDown(context);
+
+ IDisposable disposable = context.TestObject as IDisposable;
+ if (disposable != null && Test is IDisposableFixture)
+ disposable.Dispose();
+ }
+ catch (Exception ex)
+ {
+ suiteResult.RecordTearDownException(ex);
+ }
+
+ return suiteResult;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Threading;
+
+namespace NUnit.Framework.Internal.Commands
+{
+ using Execution;
+ using Interfaces;
+ using NUnit.Framework.TUnit;
+
+ /// <summary>
+ /// SetUpTearDownCommand runs any SetUp methods for a suite,
+ /// runs the test and then runs any TearDown methods.
+ /// </summary>
+ public class SetUpTearDownCommand : DelegatingTestCommand
+ {
+ private IList<SetUpTearDownItem> _setUpTearDownItems;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SetUpTearDownCommand"/> class.
+ /// </summary>
+ /// <param name="innerCommand">The inner command.</param>
+ public SetUpTearDownCommand(TestCommand innerCommand)
+ : base(innerCommand)
+ {
+ Guard.ArgumentValid(innerCommand.Test is TestMethod, "SetUpTearDownCommand may only apply to a TestMethod", "innerCommand");
+ Guard.OperationValid(Test.TypeInfo != null, "TestMethod must have a non-null TypeInfo");
+
+ _setUpTearDownItems = CommandBuilder.BuildSetUpTearDownList(Test.TypeInfo.Type, typeof(SetUpAttribute), typeof(TearDownAttribute));
+ }
+
+ /// <summary>
+ /// Runs the test, saving a TestResult in the supplied TestExecutionContext.
+ /// </summary>
+ /// <param name="context">The context in which the test should run.</param>
+ /// <returns>A TestResult</returns>
+ public override TestResult Execute(TestExecutionContext context)
+ {
+ try
+ {
+ TAsyncThreadMgr.GetInstance().ClearSetUpTearDown();
+ for (int i = _setUpTearDownItems.Count; i > 0;)
+ _setUpTearDownItems[--i].RunSetupForTC(context);
+
+ for (int i = 0; i < _setUpTearDownItems.Count; i++)
+ _setUpTearDownItems[i].RunTearDownForTC(context);
+
+ context.CurrentResult = innerCommand.Execute(context);
+ }
+ catch (Exception ex)
+ {
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ if (ex is ThreadAbortException)
+ Thread.ResetAbort();
+#endif
+ context.CurrentResult.RecordException(ex);
+ }
+
+ return context.CurrentResult;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using NUnit.Framework.TUnit;
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Threading;
+
+namespace NUnit.Framework.Internal.Commands
+{
+ /// <summary>
+ /// SetUpTearDownItem holds the setup and teardown methods
+ /// for a single level of the inheritance hierarchy.
+ /// </summary>
+ public class SetUpTearDownItem
+ {
+ public IList<MethodInfo> _setUpMethods;
+ public IList<MethodInfo> _tearDownMethods;
+ public bool _setUpWasRun;
+
+ /// <summary>
+ /// Construct a SetUpTearDownNode
+ /// </summary>
+ /// <param name="setUpMethods">A list of setup methods for this level</param>
+ /// <param name="tearDownMethods">A list teardown methods for this level</param>
+ public SetUpTearDownItem(IList<MethodInfo> setUpMethods, IList<MethodInfo> tearDownMethods)
+ {
+ _setUpMethods = setUpMethods;
+ _tearDownMethods = tearDownMethods;
+ }
+
+ /// <summary>
+ /// Returns true if this level has any methods at all.
+ /// This flag is used to discard levels that do nothing.
+ /// </summary>
+ public bool HasMethods
+ {
+ get { return _setUpMethods.Count > 0 || _tearDownMethods.Count > 0; }
+ }
+
+ /// <summary>
+ /// Run SetUp on this level.
+ /// </summary>
+ /// <param name="context">The execution context to use for running.</param>
+ public void RunSetUp(TestExecutionContext context)
+ {
+ _setUpWasRun = true;
+ foreach (MethodInfo setUpMethod in _setUpMethods)
+ RunSetUpOrTearDownMethod(context, setUpMethod);
+ }
+
+ #region add by nguyen.vtan , method use for run setup of TC on main thread
+ public void RunSetupForTC(TestExecutionContext context)
+ {
+ _setUpWasRun = true;
+ TAsyncThreadMgr asyncThreadMgr = TAsyncThreadMgr.GetInstance();
+ asyncThreadMgr.SetData(this);
+ }
+ #endregion
+ /// <summary>
+ /// Run TearDown for this level.
+ /// </summary>
+ /// <param name="context"></param>
+ public void RunTearDown(TestExecutionContext context)
+ {
+ // As of NUnit 3.0, we will only run teardown at a given
+ // inheritance level if we actually ran setup at that level.
+ if (_setUpWasRun)
+ try
+ {
+ // Even though we are only running one level at a time, we
+ // run the teardowns in reverse order to provide consistency.
+ int index = _tearDownMethods.Count;
+ while (--index >= 0)
+ {
+ RunSetUpOrTearDownMethod(context, _tearDownMethods[index]);
+ }
+ }
+ catch (Exception ex)
+ {
+ context.CurrentResult.RecordTearDownException(ex);
+ }
+ }
+
+ #region add by nguyen.vtan , method use for run teardown of TC on main thread
+ public void RunTearDownForTC(TestExecutionContext context)
+ {
+ if (_setUpWasRun)
+ try
+ {
+ // Even though we are only running one level at a time, we
+ // run the teardowns in reverse order to provide consistency.
+ TAsyncThreadMgr asyncThreadMgr = TAsyncThreadMgr.GetInstance();
+ asyncThreadMgr.SetTearDownData(this);
+
+ }
+ catch (Exception ex)
+ {
+ context.CurrentResult.RecordTearDownException(ex);
+ }
+ }
+ #endregion
+ public void RunSetUpOrTearDownMethod(TestExecutionContext context, MethodInfo method)
+ {
+#if NET_4_0 || NET_4_5 || PORTABLE
+ if (AsyncInvocationRegion.IsAsyncOperation(method))
+ RunAsyncMethod(method, context);
+ else
+#endif
+ RunNonAsyncMethod(method, context);
+ }
+
+#if NET_4_0 || NET_4_5 || PORTABLE
+ private void RunAsyncMethod(MethodInfo method, TestExecutionContext context)
+ {
+ using (AsyncInvocationRegion region = AsyncInvocationRegion.Create(method))
+ region.WaitForPendingOperationsToComplete(RunNonAsyncMethod(method, context));
+ }
+#endif
+ private object RunNonAsyncMethod(MethodInfo method, TestExecutionContext context)
+ {
+ return Reflect.InvokeMethod(method, method.IsStatic ? null : context.TestObject);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Commands
+{
+ /// <summary>
+ /// TODO: Documentation needed for class
+ /// </summary>
+ public class SkipCommand : TestCommand
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SkipCommand"/> class.
+ /// </summary>
+ /// <param name="test">The test being skipped.</param>
+ public SkipCommand(Test test) : base(test)
+ {
+ }
+
+ /// <summary>
+ /// Overridden to simply set the CurrentResult to the
+ /// appropriate Skipped state.
+ /// </summary>
+ /// <param name="context">The execution context for the test</param>
+ /// <returns>A TestResult</returns>
+ public override TestResult Execute(TestExecutionContext context)
+ {
+ TestResult testResult = context.CurrentResult;
+
+ switch (Test.RunState)
+ {
+ default:
+ case RunState.Skipped:
+ testResult.SetResult(ResultState.Skipped, GetSkipReason());
+ break;
+ case RunState.Ignored:
+ testResult.SetResult(ResultState.Ignored, GetSkipReason());
+ break;
+ case RunState.Explicit:
+ testResult.SetResult(ResultState.Explicit, GetSkipReason());
+ break;
+ case RunState.NotRunnable:
+ testResult.SetResult(ResultState.NotRunnable, GetSkipReason(), GetProviderStackTrace());
+ break;
+ }
+
+ return testResult;
+ }
+
+ private string GetSkipReason()
+ {
+ return (string)Test.Properties.Get(PropertyNames.SkipReason);
+ }
+
+ private string GetProviderStackTrace()
+ {
+ return (string)Test.Properties.Get(PropertyNames.ProviderStackTrace);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Threading;
+
+namespace NUnit.Framework.Internal.Commands
+{
+ using Interfaces;
+
+ /// <summary>
+ /// TestActionCommand runs the BeforeTest actions for a test,
+ /// then runs the test and finally runs the AfterTestActions.
+ /// </summary>
+ public class TestActionCommand : DelegatingTestCommand
+ {
+ private IList<TestActionItem> _actions = new List<TestActionItem>();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestActionCommand"/> class.
+ /// </summary>
+ /// <param name="innerCommand">The inner command.</param>
+ public TestActionCommand(TestCommand innerCommand)
+ : base(innerCommand)
+ {
+ Guard.ArgumentValid(innerCommand.Test is TestMethod, "TestActionCommand may only apply to a TestMethod", "innerCommand");
+ }
+
+ /// <summary>
+ /// Runs the test, saving a TestResult in the supplied TestExecutionContext.
+ /// </summary>
+ /// <param name="context">The context in which the test should run.</param>
+ /// <returns>A TestResult</returns>
+ public override TestResult Execute(TestExecutionContext context)
+ {
+ if (Test.Fixture == null)
+ Test.Fixture = context.TestObject;
+
+ // In the current implementation, upstream actions only apply to tests. If that should change in the future,
+ // then actions would have to be tested for here. For now we simply assert it in Debug. We allow
+ // ActionTargets.Default, because it is passed down by ParameterizedMethodSuite.
+ foreach (ITestAction action in context.UpstreamActions)
+ {
+ System.Diagnostics.Debug.Assert(
+ action.Targets == ActionTargets.Default || (action.Targets & ActionTargets.Test) == ActionTargets.Test,
+ "Invalid target on upstream action: " + action.Targets.ToString());
+
+ _actions.Add(new TestActionItem(action));
+ }
+
+ //foreach (ITestAction action in ActionsHelper.GetActionsFromAttributeProvider(((TestMethod)Test).Method.MethodInfo))
+ // if (action.Targets == ActionTargets.Default || (action.Targets & ActionTargets.Test) == ActionTargets.Test)
+ // _actions.Add(new TestActionItem(action));
+
+ try
+ {
+ for (int i = 0; i < _actions.Count; i++)
+ _actions[i].BeforeTest(Test);
+
+ context.CurrentResult = innerCommand.Execute(context);
+ }
+ catch (Exception ex)
+ {
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ if (ex is ThreadAbortException)
+ Thread.ResetAbort();
+#endif
+ context.CurrentResult.RecordException(ex);
+ }
+ finally
+ {
+ if (context.ExecutionStatus != TestExecutionStatus.AbortRequested)
+ for (int i = _actions.Count - 1; i >= 0; i--)
+ _actions[i].AfterTest(Test);
+ }
+
+ return context.CurrentResult;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+
+namespace NUnit.Framework.Internal.Commands
+{
+ /// <summary>
+ /// TestActionItem represents a single execution of an
+ /// ITestAction. It is used to track whether the BeforeTest
+ /// method has been called and suppress calling the
+ /// AfterTest method if it has not.
+ /// </summary>
+ public class TestActionItem
+ {
+ private readonly ITestAction _action;
+ private bool _beforeTestWasRun;
+
+ /// <summary>
+ /// Construct a TestActionItem
+ /// </summary>
+ /// <param name="action">The ITestAction to be included</param>
+ public TestActionItem(ITestAction action)
+ {
+ _action = action;
+ }
+
+ /// <summary>
+ /// Run the BeforeTest method of the action and remember that it has been run.
+ /// </summary>
+ /// <param name="test">The test to which the action applies</param>
+ public void BeforeTest(Interfaces.ITest test)
+ {
+ _beforeTestWasRun = true;
+ _action.BeforeTest(test);
+ }
+
+ /// <summary>
+ /// Run the AfterTest action, but only if the BeforeTest
+ /// action was actually run.
+ /// </summary>
+ /// <param name="test">The test to which the action applies</param>
+ public void AfterTest(Interfaces.ITest test)
+ {
+ if (_beforeTestWasRun)
+ _action.AfterTest(test);
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Threading;
+
+namespace NUnit.Framework.Internal.Commands
+{
+ /// <summary>
+ /// TestCommand is the abstract base class for all test commands
+ /// in the framework. A TestCommand represents a single stage in
+ /// the execution of a test, e.g.: SetUp/TearDown, checking for
+ /// Timeout, verifying the returned result from a method, etc.
+ ///
+ /// TestCommands may decorate other test commands so that the
+ /// execution of a lower-level command is nested within that
+ /// of a higher level command. All nested commands are executed
+ /// synchronously, as a single unit. Scheduling test execution
+ /// on separate threads is handled at a higher level, using the
+ /// task dispatcher.
+ /// </summary>
+ public abstract class TestCommand
+ {
+ /// <summary>
+ /// Construct a TestCommand for a test.
+ /// </summary>
+ /// <param name="test">The test to be executed</param>
+ public TestCommand(Test test)
+ {
+ this.Test = test;
+ }
+
+ #region Public Methods
+
+ /// <summary>
+ /// Gets the test associated with this command.
+ /// </summary>
+ public Test Test { get; private set; }
+
+ /// <summary>
+ /// Runs the test in a specified context, returning a TestResult.
+ /// </summary>
+ /// <param name="context">The TestExecutionContext to be used for running the test.</param>
+ /// <returns>A TestResult</returns>
+ public abstract TestResult Execute(TestExecutionContext context);
+
+ #endregion
+
+ #region tronghieu.d - Declear ManualResetEvent object for block current thread to handle result from invoking test method.
+
+ public ManualResetEvent _testMethodRunComplete = new ManualResetEvent(false);
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Commands
+{
+ /// <summary>
+ /// TestMethodCommand is the lowest level concrete command
+ /// used to run actual test cases.
+ /// </summary>
+ public class TestMethodCommand : TestCommand
+ {
+ private readonly TestMethod testMethod;
+ private readonly object[] arguments;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestMethodCommand"/> class.
+ /// </summary>
+ /// <param name="testMethod">The test.</param>
+ public TestMethodCommand(TestMethod testMethod) : base(testMethod)
+ {
+ this.testMethod = testMethod;
+ this.arguments = testMethod.Arguments;
+ }
+
+ /// <summary>
+ /// Runs the test, saving a TestResult in the execution context, as
+ /// well as returning it. If the test has an expected result, it
+ /// is asserts on that value. Since failed tests and errors throw
+ /// an exception, this command must be wrapped in an outer command,
+ /// will handle that exception and records the failure. This role
+ /// is usually played by the SetUpTearDown command.
+ /// </summary>
+ /// <param name="context">The execution context</param>
+ public override TestResult Execute(TestExecutionContext context)
+ {
+ // TODO: Decide if we should handle exceptions here
+ object result = RunTestMethod(context);
+
+ if (testMethod.HasExpectedResult)
+ NUnit.Framework.Assert.AreEqual(testMethod.ExpectedResult, result);
+
+ context.CurrentResult.SetResult(ResultState.Success);
+ // TODO: Set assert count here?
+ //context.CurrentResult.AssertCount = context.AssertCount;
+ return context.CurrentResult;
+ }
+
+ private object RunTestMethod(TestExecutionContext context)
+ {
+#if NET_4_0 || NET_4_5 || PORTABLE
+ if (AsyncInvocationRegion.IsAsyncOperation(testMethod.Method.MethodInfo))
+ return RunAsyncTestMethod(context);
+ else
+#endif
+ return RunNonAsyncTestMethod(context);
+ }
+
+#if NET_4_0 || NET_4_5 || PORTABLE
+ private object RunAsyncTestMethod(TestExecutionContext context)
+ {
+ using (AsyncInvocationRegion region = AsyncInvocationRegion.Create(testMethod.Method.MethodInfo))
+ {
+ object result = Reflect.InvokeMethod(testMethod.Method.MethodInfo, context.TestObject, arguments);
+
+ try
+ {
+ return region.WaitForPendingOperationsToComplete(result);
+ }
+ catch (Exception e)
+ {
+ throw new NUnitException("Rethrown", e);
+ }
+ }
+ }
+#endif
+
+ private object RunNonAsyncTestMethod(TestExecutionContext context)
+ {
+ //return Reflect.InvokeMethod(testMethod.Method.MethodInfo, context.TestObject, arguments);
+ return testMethod.Method.Invoke(context.TestObject, arguments);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Commands
+{
+ /// <summary>
+ /// TheoryResultCommand adjusts the result of a Theory so that
+ /// it fails if all the results were inconclusive.
+ /// </summary>
+ public class TheoryResultCommand : DelegatingTestCommand
+ {
+ /// <summary>
+ /// Constructs a TheoryResultCommand
+ /// </summary>
+ /// <param name="command">The command to be wrapped by this one</param>
+ public TheoryResultCommand(TestCommand command) : base(command) { }
+
+ /// <summary>
+ /// Overridden to call the inner command and adjust the result
+ /// in case all chlid results were inconclusive.
+ /// </summary>
+ /// <param name="context"></param>
+ /// <returns></returns>
+ public override TestResult Execute(TestExecutionContext context)
+ {
+ TestResult theoryResult = innerCommand.Execute(context);
+
+ if (theoryResult.ResultState == ResultState.Success)
+ {
+ if (!theoryResult.HasChildren)
+ theoryResult.SetResult(ResultState.Failure, "No test cases were provided");
+ else
+ {
+ bool wasInconclusive = true;
+ foreach (TestResult childResult in theoryResult.Children)
+ if (childResult.ResultState == ResultState.Success)
+ {
+ wasInconclusive = false;
+ break;
+ }
+
+ if (wasInconclusive)
+ theoryResult.SetResult(ResultState.Failure, "All test cases were inconclusive");
+ }
+ }
+
+ return theoryResult;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Globalization;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// CultureDetector is a helper class used by NUnit to determine
+ /// whether a test should be run based on the current culture.
+ /// </summary>
+ public class CultureDetector
+ {
+ private CultureInfo currentCulture;
+
+ // Set whenever we fail to support a list of platforms
+ private string reason = string.Empty;
+
+ /// <summary>
+ /// Default constructor uses the current culture.
+ /// </summary>
+ public CultureDetector()
+ {
+ this.currentCulture = CultureInfo.CurrentCulture;
+ }
+
+ /// <summary>
+ /// Construct a CultureDetector for a particular culture for testing.
+ /// </summary>
+ /// <param name="culture">The culture to be used</param>
+ public CultureDetector( string culture )
+ {
+ this.currentCulture = new CultureInfo( culture );
+ }
+
+ /// <summary>
+ /// Test to determine if one of a collection of cultures
+ /// is being used currently.
+ /// </summary>
+ /// <param name="cultures"></param>
+ /// <returns></returns>
+ public bool IsCultureSupported( string[] cultures )
+ {
+ foreach( string culture in cultures )
+ if ( IsCultureSupported( culture ) )
+ return true;
+
+ return false;
+ }
+
+ /// <summary>
+ /// Tests to determine if the current culture is supported
+ /// based on a culture attribute.
+ /// </summary>
+ /// <param name="cultureAttribute">The attribute to examine</param>
+ /// <returns></returns>
+ public bool IsCultureSupported( CultureAttribute cultureAttribute )
+ {
+ string include = cultureAttribute.Include;
+ string exclude = cultureAttribute.Exclude;
+
+ //try
+ //{
+ if (include != null && !IsCultureSupported(include))
+ {
+ reason = string.Format("Only supported under culture {0}", include);
+ return false;
+ }
+
+ if (exclude != null && IsCultureSupported(exclude))
+ {
+ reason = string.Format("Not supported under culture {0}", exclude);
+ return false;
+ }
+ //}
+ //catch( ArgumentException ex )
+ //{
+ // reason = string.Format( "Invalid culture: {0}", ex.ParamName );
+ // return false;
+ //}
+
+ return true;
+ }
+
+ /// <summary>
+ /// Test to determine if the a particular culture or comma-
+ /// delimited set of cultures is in use.
+ /// </summary>
+ /// <param name="culture">Name of the culture or comma-separated list of culture ids</param>
+ /// <returns>True if the culture is in use on the system</returns>
+ public bool IsCultureSupported( string culture )
+ {
+ culture = culture.Trim();
+
+ if ( culture.IndexOf( ',' ) >= 0 )
+ {
+ if ( IsCultureSupported( culture.Split( new char[] { ',' } ) ) )
+ return true;
+ }
+ else
+ {
+ if( this.currentCulture.Name == culture || this.currentCulture.TwoLetterISOLanguageName == culture)
+ return true;
+ }
+
+ this.reason = "Only supported under culture " + culture;
+ return false;
+ }
+
+ /// <summary>
+ /// Return the last failure reason. Results are not
+ /// defined if called before IsSupported( Attribute )
+ /// is called.
+ /// </summary>
+ public string Reason
+ {
+ get { return reason; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Globalization;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Text;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// ExceptionHelper provides static methods for working with exceptions
+ /// </summary>
+ public class ExceptionHelper
+ {
+#if !NET_4_5 && !PORTABLE && !SILVERLIGHT && !NETCF
+ private static readonly Action<Exception> PreserveStackTrace;
+
+ static ExceptionHelper()
+ {
+ var method = typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
+
+ if (method != null)
+ {
+ try
+ {
+ PreserveStackTrace = (Action<Exception>)Delegate.CreateDelegate(typeof(Action<Exception>), method);
+ return;
+ }
+ catch (InvalidOperationException) { }
+ }
+ PreserveStackTrace = _ => { };
+ }
+#endif
+
+#if !NETCF && !SILVERLIGHT
+ /// <summary>
+ /// Rethrows an exception, preserving its stack trace
+ /// </summary>
+ /// <param name="exception">The exception to rethrow</param>
+ public static void Rethrow(Exception exception)
+ {
+#if NET_4_5 || PORTABLE
+ System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(exception).Throw();
+#else
+ PreserveStackTrace(exception);
+ throw exception;
+#endif
+ }
+#endif
+
+ // TODO: Move to a utility class
+ /// <summary>
+ /// Builds up a message, using the Message field of the specified exception
+ /// as well as any InnerExceptions.
+ /// </summary>
+ /// <param name="exception">The exception.</param>
+ /// <returns>A combined message string.</returns>
+ public static string BuildMessage(Exception exception)
+ {
+ StringBuilder sb = new StringBuilder();
+ sb.AppendFormat(CultureInfo.CurrentCulture, "{0} : {1}", exception.GetType().ToString(), exception.Message);
+
+ foreach (Exception inner in FlattenExceptionHierarchy(exception))
+ {
+ sb.Append(NUnit.Env.NewLine);
+ sb.AppendFormat(CultureInfo.CurrentCulture, " ----> {0} : {1}", inner.GetType().ToString(), inner.Message);
+ }
+
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// Builds up a message, using the Message field of the specified exception
+ /// as well as any InnerExceptions.
+ /// </summary>
+ /// <param name="exception">The exception.</param>
+ /// <returns>A combined stack trace.</returns>
+ public static string BuildStackTrace(Exception exception)
+ {
+ StringBuilder sb = new StringBuilder(GetStackTrace(exception));
+
+ foreach (Exception inner in FlattenExceptionHierarchy(exception))
+ {
+ sb.Append(NUnit.Env.NewLine);
+ sb.Append("--");
+ sb.Append(inner.GetType().Name);
+ sb.Append(NUnit.Env.NewLine);
+ sb.Append(GetStackTrace(inner));
+ }
+
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// Gets the stack trace of the exception.
+ /// </summary>
+ /// <param name="exception">The exception.</param>
+ /// <returns>A string representation of the stack trace.</returns>
+ public static string GetStackTrace(Exception exception)
+ {
+ try
+ {
+ return exception.StackTrace;
+ }
+ catch (Exception)
+ {
+ return "No stack trace available";
+ }
+ }
+
+ private static List<Exception> FlattenExceptionHierarchy(Exception exception)
+ {
+ var result = new List<Exception>();
+
+#if NET_4_0 || NET_4_5 || SILVERLIGHT || PORTABLE
+ if (exception is AggregateException)
+ {
+ var aggregateException = (exception as AggregateException);
+ result.AddRange(aggregateException.InnerExceptions);
+
+ foreach (var innerException in aggregateException.InnerExceptions)
+ result.AddRange(FlattenExceptionHierarchy(innerException));
+ }
+ else
+#endif
+ if (exception.InnerException != null)
+ {
+ result.Add(exception.InnerException);
+ result.AddRange(FlattenExceptionHierarchy(exception.InnerException));
+ }
+
+ return result;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+using System.Collections.Generic;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+
+#if TIZEN
+using NUnit.Framework.TUnit;
+#endif
+
+namespace NUnit.Framework.Internal.Execution
+{
+ using Commands;
+ using Interfaces;
+
+ /// <summary>
+ /// A utility class to create TestCommands
+ /// </summary>
+ public static class CommandBuilder
+ {
+ /// <summary>
+ /// Gets the command to be executed before any of
+ /// the child tests are run.
+ /// </summary>
+ /// <returns>A TestCommand</returns>
+ public static TestCommand MakeOneTimeSetUpCommand(TestSuite suite, List<SetUpTearDownItem> setUpTearDown, List<TestActionItem> actions)
+ {
+ // Handle skipped tests
+ if (suite.RunState != RunState.Runnable && suite.RunState != RunState.Explicit)
+ return MakeSkipCommand(suite);
+
+ // Build the OneTimeSetUpCommand itself
+ TestCommand command = new OneTimeSetUpCommand(suite, setUpTearDown, actions);
+
+ // Prefix with any IApplyToContext items from attributes
+ IList<IApplyToContext> changes = null;
+
+ if (suite.TypeInfo != null)
+ changes = (IApplyToContext[])suite.TypeInfo.GetCustomAttributes<IApplyToContext>(true);
+ else if (suite.Method != null)
+ changes = (IApplyToContext[])suite.Method.GetCustomAttributes<IApplyToContext>(true);
+ else
+ {
+ var testAssembly = suite as TestAssembly;
+ if (testAssembly != null)
+#if PORTABLE
+ //changes = new List<IApplyToContext>(testAssembly.Assembly.GetAttributes<IApplyToContext>());
+ changes = new List<IApplyToContext>();
+#else
+ changes = (IApplyToContext[])testAssembly.Assembly.GetCustomAttributes(typeof(IApplyToContext), true);
+#endif
+ }
+
+ if (changes != null && changes.Count > 0)
+ command = new ApplyChangesToContextCommand(command, changes);
+
+ return command;
+ }
+
+ /// <summary>
+ /// Gets the command to be executed after all of the
+ /// child tests are run.
+ /// </summary>
+ /// <returns>A TestCommand</returns>
+ public static TestCommand MakeOneTimeTearDownCommand(TestSuite suite, List<SetUpTearDownItem> setUpTearDownItems, List<TestActionItem> actions)
+ {
+ // Build the OneTimeTearDown command itself
+ TestCommand command = new OneTimeTearDownCommand(suite, setUpTearDownItems, actions);
+
+ // For Theories, follow with TheoryResultCommand to adjust result as needed
+ if (suite.TestType == "Theory")
+ command = new TheoryResultCommand(command);
+
+ return command;
+ }
+
+ /// <summary>
+ /// Creates a test command for use in running this test.
+ /// </summary>
+ /// <returns></returns>
+ public static TestCommand MakeTestCommand(TestMethod test)
+ {
+ // Command to execute test
+#if TIZEN
+ // [DuongNT]: Create Tizen TestMethod command instance
+ TestCommand command = new TTestMethodCommand(test);
+#else
+ TestCommand command = new TestMethodCommand(test);
+#endif
+ // Add any wrappers to the TestMethodCommand
+ foreach (IWrapTestMethod wrapper in test.Method.GetCustomAttributes<IWrapTestMethod>(true))
+ command = wrapper.Wrap(command);
+
+ // Wrap in TestActionCommand
+ command = new TestActionCommand(command);
+
+ // Wrap in SetUpTearDownCommand
+ command = new SetUpTearDownCommand(command);
+
+ // Add wrappers that apply before setup and after teardown
+ foreach (ICommandWrapper decorator in test.Method.GetCustomAttributes<IWrapSetUpTearDown>(true))
+ command = decorator.Wrap(command);
+
+ // Add command to set up context using attributes that implement IApplyToContext
+ IApplyToContext[] changes = (IApplyToContext[])test.Method.GetCustomAttributes<IApplyToContext>(true);
+ if (changes.Length > 0)
+ command = new ApplyChangesToContextCommand(command, changes);
+
+ return command;
+ }
+
+ /// <summary>
+ /// Creates a command for skipping a test. The result returned will
+ /// depend on the test RunState.
+ /// </summary>
+ public static SkipCommand MakeSkipCommand(Test test)
+ {
+ return new SkipCommand(test);
+ }
+
+ /// <summary>
+ /// Builds the set up tear down list.
+ /// </summary>
+ /// <param name="fixtureType">Type of the fixture.</param>
+ /// <param name="setUpType">Type of the set up attribute.</param>
+ /// <param name="tearDownType">Type of the tear down attribute.</param>
+ /// <returns>A list of SetUpTearDownItems</returns>
+ public static List<SetUpTearDownItem> BuildSetUpTearDownList(Type fixtureType, Type setUpType, Type tearDownType)
+ {
+ var setUpMethods = Reflect.GetMethodsWithAttribute(fixtureType, setUpType, true);
+ var tearDownMethods = Reflect.GetMethodsWithAttribute(fixtureType, tearDownType, true);
+
+ var list = new List<SetUpTearDownItem>();
+
+ while (fixtureType != null && !fixtureType.Equals(typeof(object)))
+ {
+ var node = BuildNode(fixtureType, setUpMethods, tearDownMethods);
+ if (node.HasMethods)
+ list.Add(node);
+
+ fixtureType = fixtureType.GetTypeInfo().BaseType;
+ }
+
+ return list;
+ }
+
+ // This method builds a list of nodes that can be used to
+ // run setup and teardown according to the NUnit specs.
+ // We need to execute setup and teardown methods one level
+ // at a time. However, we can't discover them by reflection
+ // one level at a time, because that would cause overridden
+ // methods to be called twice, once on the base class and
+ // once on the derived class.
+ //
+ // For that reason, we start with a list of all setup and
+ // teardown methods, found using a single reflection call,
+ // and then descend through the inheritance hierarchy,
+ // adding each method to the appropriate level as we go.
+ private static SetUpTearDownItem BuildNode(Type fixtureType, IList<MethodInfo> setUpMethods, IList<MethodInfo> tearDownMethods)
+ {
+ // Create lists of methods for this level only.
+ // Note that FindAll can't be used because it's not
+ // available on all the platforms we support.
+ var mySetUpMethods = SelectMethodsByDeclaringType(fixtureType, setUpMethods);
+ var myTearDownMethods = SelectMethodsByDeclaringType(fixtureType, tearDownMethods);
+
+ return new SetUpTearDownItem(mySetUpMethods, myTearDownMethods);
+ }
+
+ private static List<MethodInfo> SelectMethodsByDeclaringType(Type type, IList<MethodInfo> methods)
+ {
+ var list = new List<MethodInfo>();
+
+ foreach (var method in methods)
+ if (method.DeclaringType == type)
+ list.Add(method);
+
+ return list;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Internal.Commands;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.TUnit;
+using System.Collections.Concurrent;
+using System.Threading.Tasks;
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// A CompositeWorkItem represents a test suite and
+ /// encapsulates the execution of the suite as well
+ /// as all its child tests.
+ /// </summary>
+ public class CompositeWorkItem : WorkItem
+ {
+ // static Logger log = InternalTrace.GetLogger("CompositeWorkItem");
+
+ private TestSuite _suite;
+ private TestSuiteResult _suiteResult;
+ private ITestFilter _childFilter;
+ private TestCommand _setupCommand;
+ private TestCommand _teardownCommand;
+ private List<WorkItem> _children;
+ private TSettings tsettings;
+
+ /// <summary>
+ /// List of Child WorkItems
+ /// </summary>
+ public List<WorkItem> Children
+ {
+ get { return _children; }
+ private set { _children = value; }
+ }
+
+ /// <summary>
+ /// A count of how many tests in the work item have a value for the Order Property
+ /// </summary>
+ private int _countOrder;
+
+ private CountdownEvent _childTestCountdown;
+
+ /// <summary>
+ /// Construct a CompositeWorkItem for executing a test suite
+ /// using a filter to select child tests.
+ /// </summary>
+ /// <param name="suite">The TestSuite to be executed</param>
+ /// <param name="childFilter">A filter used to select child tests</param>
+ public CompositeWorkItem(TestSuite suite, ITestFilter childFilter)
+ : base(suite)
+ {
+ _suite = suite;
+ _suiteResult = Result as TestSuiteResult;
+ _childFilter = childFilter;
+ _countOrder = 0;
+ tsettings = TSettings.GetInstance();
+ }
+
+ /// <summary>
+ /// Method that actually performs the work. Overridden
+ /// in CompositeWorkItem to do setup, run all child
+ /// items and then do teardown.
+ /// </summary>
+ protected override void PerformWork()
+ {
+ // Inititialize actions, setup and teardown
+ // We can't do this in the constructor because
+ // the context is not available at that point.
+ InitializeSetUpAndTearDownCommands();
+
+ if (!CheckForCancellation())
+ // [tronghieu.d] - Add more conditions for check slave mode
+ if (Test.TestType.Equals("Assembly") || !tsettings.IsSlaveMode || tsettings.Testcase_ID.Contains(Test.FullName))
+ // [tronghieu.d] - end
+ if (Test.RunState == RunState.Explicit && !_childFilter.IsExplicitMatch(Test))
+ SkipFixture(ResultState.Explicit, GetSkipReason(), null);
+ else
+ switch (Test.RunState)
+ {
+ default:
+ case RunState.Runnable:
+ case RunState.Explicit:
+ // Assume success, since the result will be inconclusive
+ // if there is no setup method to run or if the
+ // context initialization fails.
+ Result.SetResult(ResultState.Success);
+
+ if (_children == null)
+ CreateChildWorkItems();
+
+ if (_children.Count > 0)
+ {
+ PerformOneTimeSetUp();
+
+ if (!CheckForCancellation())
+ switch (Result.ResultState.Status)
+ {
+ case TestStatus.Passed:
+ RunChildren();
+ return;
+ // Just return: completion event will take care
+ // of TestFixtureTearDown when all tests are done.
+
+ case TestStatus.Skipped:
+ case TestStatus.Inconclusive:
+ case TestStatus.Failed:
+ SkipChildren(_suite, Result.ResultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + Result.Message);
+ break;
+ }
+
+ // Directly execute the OneTimeFixtureTearDown for tests that
+ // were skipped, failed or set to inconclusive in one time setup
+ // unless we are aborting.
+ if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested)
+ PerformOneTimeTearDown();
+ }
+ break;
+
+ case RunState.Skipped:
+ SkipFixture(ResultState.Skipped, GetSkipReason(), null);
+ break;
+
+ case RunState.Ignored:
+ SkipFixture(ResultState.Ignored, GetSkipReason(), null);
+ break;
+
+ case RunState.NotRunnable:
+ SkipFixture(ResultState.NotRunnable, GetSkipReason(), GetProviderStackTrace());
+ break;
+ }
+
+ // Fall through in case nothing was run.
+ // Otherwise, this is done in the completion event.
+ WorkItemComplete();
+
+ }
+
+ #region Helper Methods
+
+ private bool CheckForCancellation()
+ {
+ if (Context.ExecutionStatus != TestExecutionStatus.Running)
+ {
+ Result.SetResult(ResultState.Cancelled, "Test cancelled by user");
+ return true;
+ }
+
+ return false;
+ }
+
+ private void InitializeSetUpAndTearDownCommands()
+ {
+ List<SetUpTearDownItem> setUpTearDownItems = _suite.TypeInfo != null
+ ? CommandBuilder.BuildSetUpTearDownList(_suite.TypeInfo.Type, typeof(OneTimeSetUpAttribute), typeof(OneTimeTearDownAttribute))
+ : new List<SetUpTearDownItem>();
+
+ var actionItems = new List<TestActionItem>();
+ foreach (ITestAction action in Actions)
+ {
+ // Special handling here for ParameterizedMethodSuite is a bit ugly. However,
+ // it is needed because Tests are not supposed to know anything about Action
+ // Attributes (or any attribute) and Attributes don't know where they were
+ // initially applied unless we tell them.
+ //
+ // ParameterizedMethodSuites and individual test cases both use the same
+ // MethodInfo as a source of attributes. We handle the Test and Default targets
+ // in the test case, so we don't want to doubly handle it here.
+ bool applyToSuite = (action.Targets & ActionTargets.Suite) == ActionTargets.Suite
+ || action.Targets == ActionTargets.Default && !(Test is ParameterizedMethodSuite);
+
+ bool applyToTest = (action.Targets & ActionTargets.Test) == ActionTargets.Test
+ && !(Test is ParameterizedMethodSuite);
+
+ if (applyToSuite)
+ actionItems.Add(new TestActionItem(action));
+
+ if (applyToTest)
+ Context.UpstreamActions.Add(action);
+ }
+
+ _setupCommand = CommandBuilder.MakeOneTimeSetUpCommand(_suite, setUpTearDownItems, actionItems);
+ _teardownCommand = CommandBuilder.MakeOneTimeTearDownCommand(_suite, setUpTearDownItems, actionItems);
+ }
+
+ private void PerformOneTimeSetUp()
+ {
+ try
+ {
+ _setupCommand.Execute(Context);
+
+ // SetUp may have changed some things in the environment
+ Context.UpdateContextFromEnvironment();
+ }
+ catch (Exception ex)
+ {
+ if (ex is NUnitException || ex is TargetInvocationException)
+ ex = ex.InnerException;
+
+ Result.RecordException(ex, FailureSite.SetUp);
+ }
+ }
+
+ private void RunChildren()
+ {
+ int childCount = _children.Count;
+ if (childCount == 0)
+ throw new InvalidOperationException("RunChildren called but item has no children");
+
+ _childTestCountdown = new CountdownEvent(childCount);
+
+ foreach (WorkItem child in _children)
+ {
+ if (CheckForCancellation())
+ break;
+
+
+ #region tronghieu.d - testkit-stub
+#if TIZEN
+ if (child is CompositeWorkItem || !tsettings.IsManual
+ || child.Test.FullName.Equals(tsettings.Testcase_ID))
+#endif
+ #endregion
+ {
+ if (child is SimpleWorkItem && tsettings.IsSlaveMode && !child.Test.FullName.Equals(tsettings.Testcase_ID)) continue;
+ child.Completed += new EventHandler(OnChildCompleted);
+ if (child.Context == null)
+ {
+ child.InitializeContext(new TestExecutionContext(Context));
+ }
+ Context.Dispatcher.Dispatch(child);
+ childCount--;
+ }
+ }
+
+ if (childCount > 0)
+ {
+ while (childCount-- > 0)
+ CountDownChildTest();
+ }
+ }
+
+ private void CreateChildWorkItems()
+ {
+ _children = new List<WorkItem>();
+
+ foreach (ITest test in _suite.Tests)
+ {
+ if (_childFilter.Pass(test))
+ {
+ var child = WorkItem.CreateWorkItem(test, _childFilter);
+ child.WorkerId = this.WorkerId;
+
+#if !PORTABLE && !SILVERLIGHT && !NETCF
+ if (child.TargetApartment == ApartmentState.Unknown && TargetApartment != ApartmentState.Unknown)
+ child.TargetApartment = TargetApartment;
+#endif
+
+ if (test.Properties.ContainsKey(PropertyNames.Order))
+ {
+ _children.Insert(0, child);
+ _countOrder++;
+ }
+ else
+ {
+ _children.Add(child);
+ }
+ }
+ }
+
+ if (_countOrder != 0) SortChildren();
+ }
+
+ private class WorkItemOrderComparer : IComparer<WorkItem>
+ {
+ /// <summary>
+ /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
+ /// </summary>
+ /// <returns>
+ /// A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>, as shown in the following table.Value Meaning Less than zero<paramref name="x"/> is less than <paramref name="y"/>.Zero<paramref name="x"/> equals <paramref name="y"/>.Greater than zero<paramref name="x"/> is greater than <paramref name="y"/>.
+ /// </returns>
+ /// <param name="x">The first object to compare.</param><param name="y">The second object to compare.</param>
+ public int Compare(WorkItem x, WorkItem y)
+ {
+ var xKey = int.MaxValue;
+ var yKey = int.MaxValue;
+
+ if (x.Test.Properties.ContainsKey(PropertyNames.Order))
+ xKey = (int)x.Test.Properties[PropertyNames.Order][0];
+
+ if (y.Test.Properties.ContainsKey(PropertyNames.Order))
+ yKey = (int)y.Test.Properties[PropertyNames.Order][0];
+
+ return xKey.CompareTo(yKey);
+ }
+ }
+
+ /// <summary>
+ /// Sorts tests under this suite.
+ /// </summary>
+ private void SortChildren()
+ {
+ _children.Sort(0, _countOrder, new WorkItemOrderComparer());
+ }
+
+ private void SkipFixture(ResultState resultState, string message, string stackTrace)
+ {
+ Result.SetResult(resultState.WithSite(FailureSite.SetUp), message, StackFilter.Filter(stackTrace));
+ SkipChildren(_suite, resultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + message);
+ }
+
+ private void SkipChildren(TestSuite suite, ResultState resultState, string message)
+ {
+ foreach (Test child in suite.Tests)
+ {
+ if (_childFilter.Pass(child))
+ {
+ TestResult childResult = child.MakeTestResult();
+ childResult.SetResult(resultState, message);
+ _suiteResult.AddResult(childResult);
+#if TIZEN
+ //[tronghieu.d] - return FAIL TC in case it is skipped.
+ if (tsettings.IsSlaveMode && childResult.FullName.Equals(tsettings.Testcase_ID))
+ {
+ tsettings.TCResult = "FAIL";
+ tsettings.TCMessage = childResult.Message;
+ string json = "case_id=" + tsettings.Testcase_ID + "&result=" + tsettings.TCResult + "&msg=" + tsettings.TCMessage + "\n" + childResult.StackTrace;
+ if (!tsettings.IsManual)
+ {
+ tsettings.RequestPOST("commit_result", json);
+ tsettings.NextStepRequest();
+ }
+ else
+ tsettings.RequestPOST("commit_manual_result", json);
+ }
+#endif
+ // Some runners may depend on getting the TestFinished event
+ // even for tests that have been skipped at a higher level.
+ Context.Listener.TestFinished(childResult);
+
+ if (child.IsSuite)
+ SkipChildren((TestSuite)child, resultState, message);
+ }
+ }
+ }
+
+ private void PerformOneTimeTearDown()
+ {
+ // Our child tests or even unrelated tests may have
+ // executed on the same thread since the time that
+ // this test started, so we have to re-establish
+ // the proper execution environment
+ this.Context.EstablishExecutionEnvironment();
+ _teardownCommand.Execute(this.Context);
+ }
+
+ private string GetSkipReason()
+ {
+ return (string)Test.Properties.Get(PropertyNames.SkipReason);
+ }
+
+ private string GetProviderStackTrace()
+ {
+ return (string)Test.Properties.Get(PropertyNames.ProviderStackTrace);
+ }
+
+ private object _completionLock = new object();
+
+ private void OnChildCompleted(object sender, EventArgs e)
+ {
+ lock (_completionLock)
+ {
+ WorkItem childTask = sender as WorkItem;
+ if (childTask != null)
+ {
+ childTask.Completed -= new EventHandler(OnChildCompleted);
+#if !TIZEN
+ _suiteResult.AddResult(childTask.Result);
+#else
+ #region tronghieu.d - testkit-stub
+ if (!tsettings.IsSlaveMode && !tsettings.IsManual)
+ _suiteResult.AddResult(childTask.Result);
+ else
+ {
+ if (!_suiteResult.HasChildren)
+ _suiteResult.AddResult(childTask.Result);
+ else
+ {
+ ITestResult[] children;
+#if PARALLEL
+ var childrenAsConcurrentQueue = _suiteResult.Children as ConcurrentQueue<ITestResult>;
+ if (childrenAsConcurrentQueue != null)
+ children = childrenAsConcurrentQueue.ToArray();
+ else
+#endif
+ {
+ var childrenAsIList = Children as IList<ITestResult>;
+ if (childrenAsIList != null)
+ children = (ITestResult[])childrenAsIList;
+ else
+ throw new NotSupportedException("cannot add results to Children");
+
+ }
+ bool exist = false;
+ for (int i = 0; i < children.Length; i++)
+ {
+ if (children[i].FullName.Equals(childTask.Result.FullName))
+ {
+ exist = true;
+ break;
+ }
+ }
+ if (!exist)
+ _suiteResult.AddResult(childTask.Result);
+ }
+ if (childTask is SimpleWorkItem)
+ {
+ string result = childTask.Result.ResultState.Status.ToString();
+ if (tsettings.IsManual && tsettings.TCResult.Length != 0)
+ {
+
+ }
+ else
+ {
+ result = result.Substring(0, result.Length - 2);
+ tsettings.TCResult = result.ToUpper();
+ }
+ tsettings.Testcase_ID = childTask.Result.FullName;
+ tsettings.TCMessage = childTask.Result.Message;
+ TLogger.Write("##### Result of [" + tsettings.Testcase_ID + "] TC : " + tsettings.TCResult + " With Message: " + tsettings.TCMessage);
+
+ if (tsettings.IsSlaveMode)
+ {
+ string json = "case_id=" + tsettings.Testcase_ID + "&result=" + tsettings.TCResult + "&msg=" + tsettings.TCMessage + "\n" + childTask.Result.StackTrace;
+ if (!tsettings.IsManual)
+ {
+ tsettings.RequestPOST("commit_result", json);
+ tsettings.NextStepRequest();
+ }
+ else
+ tsettings.RequestPOST("commit_manual_result", json);
+ }
+ }
+ }
+ #endregion
+#endif
+
+ if (Context.StopOnError && childTask.Result.ResultState.Status == TestStatus.Failed)
+ Context.ExecutionStatus = TestExecutionStatus.StopRequested;
+
+ // Check to see if all children completed
+ CountDownChildTest();
+ }
+ }
+ }
+
+ private void CountDownChildTest()
+ {
+ _childTestCountdown.Signal();
+ if (_childTestCountdown.CurrentCount == 0)
+ {
+ if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested)
+ PerformOneTimeTearDown();
+
+ foreach (var childResult in _suiteResult.Children)
+ if (childResult.ResultState == ResultState.Cancelled)
+ {
+ this.Result.SetResult(ResultState.Cancelled, "Cancelled by user");
+ break;
+ }
+ WorkItemComplete();
+ }
+ }
+
+ private static bool IsStaticClass(Type type)
+ {
+ return type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed;
+ }
+
+ private object cancelLock = new object();
+
+ /// <summary>
+ /// Cancel (abort or stop) a CompositeWorkItem and all of its children
+ /// </summary>
+ /// <param name="force">true if the CompositeWorkItem and all of its children should be aborted, false if it should allow all currently running tests to complete</param>
+ public override void Cancel(bool force)
+ {
+ lock (cancelLock)
+ {
+ if (_children == null)
+ return;
+
+ foreach (var child in _children)
+ {
+ var ctx = child.Context;
+ if (ctx != null)
+ ctx.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested;
+
+ if (child.State == WorkItemState.Running)
+ child.Cancel(force);
+ }
+ }
+ }
+
+ private string GetCaseID(string TCID)
+ {
+ string[] delimiter = { "." };
+ string[] stringPieces;
+ string ClassName = "";
+ string MethodName = "";
+ stringPieces = TCID.Split(delimiter, StringSplitOptions.None);
+ for (int i = 0; i < stringPieces.Length; i++)
+ {
+ if (i == stringPieces.Length - 1)
+ MethodName = stringPieces[i];
+ else if (i == stringPieces.Length - 2)
+ ClassName = stringPieces[i];
+ }
+
+ return ClassName + "." + MethodName;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !NET_4_0 && !NET_4_5 || SILVERLIGHT
+using System.Threading;
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// A simplified implementation of .NET 4 CountdownEvent
+ /// for use in earlier versions of .NET. Only the methods
+ /// used by NUnit are implemented.
+ /// </summary>
+ public class CountdownEvent
+ {
+ int _initialCount;
+ int _remainingCount;
+ object _lock = new object();
+ ManualResetEvent _event = new ManualResetEvent(false);
+
+ /// <summary>
+ /// Construct a CountdownEvent
+ /// </summary>
+ /// <param name="initialCount">The initial count</param>
+ public CountdownEvent(int initialCount)
+ {
+ _initialCount = _remainingCount = initialCount;
+ }
+
+ /// <summary>
+ /// Gets the initial count established for the CountdownEvent
+ /// </summary>
+ public int InitialCount
+ {
+ get { return _initialCount; }
+ }
+
+ /// <summary>
+ /// Gets the current count remaining for the CountdownEvent
+ /// </summary>
+ public int CurrentCount
+ {
+ get { return _remainingCount; }
+ }
+
+ /// <summary>
+ /// Decrement the count by one
+ /// </summary>
+ public void Signal()
+ {
+ lock (_lock)
+ {
+ if (--_remainingCount == 0)
+ _event.Set();
+ }
+ }
+
+ /// <summary>
+ /// Block the thread until the count reaches zero
+ /// </summary>
+ public void Wait()
+ {
+ _event.WaitOne();
+ }
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007-2016 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+using System;
+using System.IO;
+using System.Text;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// EventListenerTextWriter sends text output to the currently active
+ /// ITestEventListener in the form of a TestOutput object. If no event
+ /// listener is active in the contet, or if there is no context,
+ /// the output is forwarded to the supplied default writer.
+ /// </summary>
+ public class EventListenerTextWriter : TextWriter
+ {
+ private TextWriter _defaultWriter;
+ private string _streamName;
+
+ /// <summary>
+ /// Construct an EventListenerTextWriter
+ /// </summary>
+ /// <param name="streamName">The name of the stream to use for events</param>
+ /// <param name="defaultWriter">The default writer to use if no listener is available</param>
+ public EventListenerTextWriter( string streamName, TextWriter defaultWriter )
+ {
+ _streamName = streamName;
+ _defaultWriter = defaultWriter;
+ }
+
+ /// <summary>
+ /// Write a single char
+ /// </summary>
+ override public void Write(char aChar)
+ {
+ if (!TrySendToListener(aChar.ToString()))
+ _defaultWriter.Write(aChar);
+ }
+
+ /// <summary>
+ /// Write a string
+ /// </summary>
+ override public void Write(string aString)
+ {
+ if (!TrySendToListener(aString))
+ _defaultWriter.Write(aString);
+ }
+
+ /// <summary>
+ /// Write a string followed by a newline
+ /// </summary>
+ override public void WriteLine(string aString)
+ {
+ if (!TrySendToListener(aString + Environment.NewLine))
+ _defaultWriter.WriteLine(aString);
+ }
+
+ /// <summary>
+ /// Get the Encoding for this TextWriter
+ /// </summary>
+ override public System.Text.Encoding Encoding
+ {
+ get { return Encoding.Default; }
+ }
+
+ private bool TrySendToListener(string text)
+ {
+ var context = TestExecutionContext.GetTestExecutionContext();
+ if (context == null || context.Listener == null)
+ return false;
+
+ string testName = context.CurrentTest != null
+ ? context.CurrentTest.FullName
+ : null;
+ context.Listener.TestOutput(new TestOutput(text, _streamName, testName));
+ return true;
+ }
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2006-2016 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if PARALLEL
+using System;
+using System.Threading;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// The EventPumpState enum represents the state of an
+ /// EventPump.
+ /// </summary>
+ public enum EventPumpState
+ {
+ /// <summary>
+ /// The pump is stopped
+ /// </summary>
+ Stopped,
+
+ /// <summary>
+ /// The pump is pumping events with no stop requested
+ /// </summary>
+ Pumping,
+
+ /// <summary>
+ /// The pump is pumping events but a stop has been requested
+ /// </summary>
+ Stopping
+ }
+
+ /// <summary>
+ /// EventPump pulls events out of an EventQueue and sends
+ /// them to a listener. It is used to send events back to
+ /// the client without using the CallContext of the test
+ /// runner thread.
+ /// </summary>
+ public class EventPump : IDisposable
+ {
+ static readonly Logger log = InternalTrace.GetLogger("EventPump");
+
+ #region Instance Variables
+
+ /// <summary>
+ /// The downstream listener to which we send events
+ /// </summary>
+ private readonly ITestListener _eventListener;
+
+ /// <summary>
+ /// The queue that holds our events
+ /// </summary>
+ private readonly EventQueue _events;
+
+ /// <summary>
+ /// Thread to do the pumping
+ /// </summary>
+ private Thread _pumpThread;
+
+ /// <summary>
+ /// The current state of the eventpump
+ /// </summary>
+ private int _pumpState = (int)EventPumpState.Stopped;
+
+ #endregion
+
+ #region Constructor
+ /// <summary>
+ /// Constructor
+ /// </summary>
+ /// <param name="eventListener">The EventListener to receive events</param>
+ /// <param name="events">The event queue to pull events from</param>
+ public EventPump( ITestListener eventListener, EventQueue events)
+ {
+ _eventListener = eventListener;
+ _events = events;
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Gets or sets the current state of the pump
+ /// </summary>
+ public EventPumpState PumpState
+ {
+ get
+ {
+ return (EventPumpState)_pumpState;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the name of this EventPump
+ /// (used only internally and for testing).
+ /// </summary>
+ public string Name { get; set; }
+
+ #endregion
+
+ #region Public Methods
+
+ /// <summary>
+ /// Dispose stops the pump
+ /// Disposes the used WaitHandle, too.
+ /// </summary>
+ public void Dispose()
+ {
+ Stop();
+ }
+
+ /// <summary>
+ /// Start the pump
+ /// </summary>
+ public void Start()
+ {
+ if ( Interlocked.CompareExchange (ref _pumpState, (int)EventPumpState.Pumping, (int)EventPumpState.Stopped) == (int)EventPumpState.Stopped) // Ignore if already started
+ {
+ _pumpThread = new Thread (PumpThreadProc)
+ {
+ Name = "EventPumpThread" + Name,
+ //Priority = ThreadPriority.Highest
+ };
+
+ _pumpThread.Start();
+ }
+ }
+
+ /// <summary>
+ /// Tell the pump to stop after emptying the queue.
+ /// </summary>
+ public void Stop()
+ {
+ if (Interlocked.CompareExchange (ref _pumpState, (int)EventPumpState.Stopping, (int)EventPumpState.Pumping) == (int)EventPumpState.Pumping)
+ {
+ _events.Stop();
+ _pumpThread.Join();
+ }
+ }
+ #endregion
+
+ #region PumpThreadProc
+
+ /// <summary>
+ /// Our thread proc for removing items from the event
+ /// queue and sending them on. Note that this would
+ /// need to do more locking if any other thread were
+ /// removing events from the queue.
+ /// </summary>
+ private void PumpThreadProc()
+ {
+ //ITestListener hostListeners = CoreExtensions.Host.Listeners;
+ try
+ {
+ while (true)
+ {
+ Event e = _events.Dequeue( PumpState == EventPumpState.Pumping );
+ if ( e == null )
+ break;
+ try
+ {
+ e.Send(_eventListener);
+ //e.Send(hostListeners);
+ }
+ catch (Exception ex)
+ {
+ log.Error( "Exception in event handler\r\n {0}", ex );
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ log.Error( "Exception in pump thread", ex );
+ }
+ finally
+ {
+ _pumpState = (int)EventPumpState.Stopped;
+ //pumpThread = null;
+ if (_events.Count > 0)
+ log.Error("Event pump thread exiting with {0} events remaining");
+ }
+ }
+ #endregion
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007-2016 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Concurrent;
+using System.Globalization;
+//using System.Runtime.Serialization;
+using System.Threading;
+#if NET_2_0 || NET_3_5 || NETCF
+using ManualResetEventSlim = System.Threading.ManualResetEvent;
+#endif
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Execution
+{
+
+#region Individual Event Classes
+
+ /// <summary>
+ /// NUnit.Core.Event is the abstract base for all stored events.
+ /// An Event is the stored representation of a call to the
+ /// ITestListener interface and is used to record such calls
+ /// or to queue them for forwarding on another thread or at
+ /// a later time.
+ /// </summary>
+ public abstract class Event
+ {
+ /// <summary>
+ /// The Send method is implemented by derived classes to send the event to the specified listener.
+ /// </summary>
+ /// <param name="listener">The listener.</param>
+ public abstract void Send(ITestListener listener);
+ }
+
+ /// <summary>
+ /// TestStartedEvent holds information needed to call the TestStarted method.
+ /// </summary>
+ public class TestStartedEvent : Event
+ {
+ private readonly ITest _test;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestStartedEvent"/> class.
+ /// </summary>
+ /// <param name="test">The test.</param>
+ public TestStartedEvent(ITest test)
+ {
+ _test = test;
+ }
+
+ /// <summary>
+ /// Calls TestStarted on the specified listener.
+ /// </summary>
+ /// <param name="listener">The listener.</param>
+ public override void Send(ITestListener listener)
+ {
+ listener.TestStarted(_test);
+ }
+ }
+
+ /// <summary>
+ /// TestFinishedEvent holds information needed to call the TestFinished method.
+ /// </summary>
+ public class TestFinishedEvent : Event
+ {
+ private readonly ITestResult _result;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestFinishedEvent"/> class.
+ /// </summary>
+ /// <param name="result">The result.</param>
+ public TestFinishedEvent(ITestResult result)
+ {
+ _result = result;
+ }
+
+ /// <summary>
+ /// Calls TestFinished on the specified listener.
+ /// </summary>
+ /// <param name="listener">The listener.</param>
+ public override void Send(ITestListener listener)
+ {
+ listener.TestFinished(_result);
+ }
+ }
+
+ /// <summary>
+ /// TestOutputEvent holds information needed to call the TestOutput method.
+ /// </summary>
+ public class TestOutputEvent : Event
+ {
+ private readonly TestOutput _output;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestOutputEvent"/> class.
+ /// </summary>
+ /// <param name="output">The output object.</param>
+ public TestOutputEvent(TestOutput output)
+ {
+ _output = output;
+ }
+
+ /// <summary>
+ /// Calls TestOutput on the specified listener.
+ /// </summary>
+ /// <param name="listener">The listener.</param>
+ public override void Send(ITestListener listener)
+ {
+ listener.TestOutput(_output);
+ }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Implements a queue of work items each of which
+ /// is queued as a WaitCallback.
+ /// </summary>
+ public class EventQueue
+ {
+ private const int spinCount = 5;
+
+// static readonly Logger log = InternalTrace.GetLogger("EventQueue");
+
+ private readonly ConcurrentQueue<Event> _queue = new ConcurrentQueue<Event>();
+
+ /* This event is used solely for the purpose of having an optimized sleep cycle when
+ * we have to wait on an external event (Add or Remove for instance)
+ */
+ private readonly ManualResetEventSlim _mreAdd = new ManualResetEventSlim(false);
+
+ /* The whole idea is to use these two values in a transactional
+ * way to track and manage the actual data inside the underlying lock-free collection
+ * instead of directly working with it or using external locking.
+ *
+ * They are manipulated with CAS and are guaranteed to increase over time and use
+ * of the instance thus preventing ABA problems.
+ */
+ private int _addId = int.MinValue;
+ private int _removeId = int.MinValue;
+
+ private int _stopped;
+
+ /// <summary>
+ /// Gets the count of items in the queue.
+ /// </summary>
+ public int Count
+ {
+ get
+ {
+ return _queue.Count;
+ }
+ }
+
+ /// <summary>
+ /// Enqueues the specified event
+ /// </summary>
+ /// <param name="e">The event to enqueue.</param>
+ public void Enqueue(Event e)
+ {
+ do
+ {
+ int cachedAddId = _addId;
+
+ // Validate that we have are the current enqueuer
+ if (Interlocked.CompareExchange(ref _addId, cachedAddId + 1, cachedAddId) != cachedAddId)
+ continue;
+
+ // Add to the collection
+ _queue.Enqueue(e);
+
+ // Wake up threads that may have been sleeping
+ _mreAdd.Set();
+
+ break;
+ } while (true);
+
+ Thread.Sleep(1); // give EventPump thread a chance to process the event
+ }
+
+ /// <summary>
+ /// Removes the first element from the queue and returns it (or <c>null</c>).
+ /// </summary>
+ /// <param name="blockWhenEmpty">
+ /// If <c>true</c> and the queue is empty, the calling thread is blocked until
+ /// either an element is enqueued, or <see cref="Stop"/> is called.
+ /// </param>
+ /// <returns>
+ /// <list type="bullet">
+ /// <item>
+ /// <term>If the queue not empty</term>
+ /// <description>the first element.</description>
+ /// </item>
+ /// <item>
+ /// <term>otherwise, if <paramref name="blockWhenEmpty"/>==<c>false</c>
+ /// or <see cref="Stop"/> has been called</term>
+ /// <description><c>null</c>.</description>
+ /// </item>
+ /// </list>
+ /// </returns>
+ public Event Dequeue(bool blockWhenEmpty)
+ {
+ SpinWait sw = new SpinWait();
+
+ do
+ {
+ int cachedRemoveId = _removeId;
+ int cachedAddId = _addId;
+
+ // Empty case
+ if (cachedRemoveId == cachedAddId)
+ {
+ if (!blockWhenEmpty || _stopped != 0)
+ return null;
+
+ // Spin a few times to see if something changes
+ if (sw.Count <= spinCount)
+ {
+ sw.SpinOnce();
+ }
+ else
+ {
+ // Reset to wait for an enqueue
+ _mreAdd.Reset();
+
+ // Recheck for an enqueue to avoid a Wait
+ if (cachedRemoveId != _removeId || cachedAddId != _addId)
+ {
+ // Queue is not empty, set the event
+ _mreAdd.Set();
+ continue;
+ }
+
+ // Wait for something to happen
+ _mreAdd.Wait(500);
+ }
+
+ continue;
+ }
+
+ // Validate that we are the current dequeuer
+ if (Interlocked.CompareExchange(ref _removeId, cachedRemoveId + 1, cachedRemoveId) != cachedRemoveId)
+ continue;
+
+
+ // Dequeue our work item
+ Event e;
+ while (!_queue.TryDequeue (out e))
+ {
+ if (!blockWhenEmpty || _stopped != 0)
+ return null;
+ }
+
+ return e;
+ } while (true);
+ }
+
+ /// <summary>
+ /// Stop processing of the queue
+ /// </summary>
+ public void Stop()
+ {
+ if (Interlocked.CompareExchange(ref _stopped, 1, 0) == 0)
+ _mreAdd.Set();
+ }
+ }
+}
+
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// An IWorkItemDispatcher handles execution of work items.
+ /// </summary>
+ public interface IWorkItemDispatcher
+ {
+ /// <summary>
+ /// Dispatch a single work item for execution. The first
+ /// work item dispatched is saved as the top-level
+ /// work item and used when stopping the run.
+ /// </summary>
+ /// <param name="work">The item to dispatch</param>
+ void Dispatch(WorkItem work);
+
+ /// <summary>
+ /// Cancel the ongoing run completely.
+ /// If no run is in process, the call has no effect.
+ /// </summary>
+ /// <param name="force">true if the IWorkItemDispatcher should abort all currently running WorkItems, false if it should allow all currently running WorkItems to complete</param>
+ void CancelRun(bool force);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012-2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#define NETCF
+#if PARALLEL
+
+using System;
+using System.Collections.Generic;
+using System.Threading;
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// ParallelWorkItemDispatcher handles execution of work items by
+ /// queuing them for worker threads to process.
+ /// </summary>
+ public class ParallelWorkItemDispatcher : IWorkItemDispatcher
+ {
+ private static readonly Logger log = InternalTrace.GetLogger("WorkItemDispatcher");
+
+ private readonly int _levelOfParallelism;
+ private int _itemsDispatched;
+
+ // Non-STA
+ private readonly WorkShift _parallelShift = new WorkShift("Parallel");
+ private readonly WorkShift _nonParallelShift = new WorkShift("NonParallel");
+ private readonly Lazy<WorkItemQueue> _parallelQueue;
+ private readonly Lazy<WorkItemQueue> _nonParallelQueue;
+
+ // STA
+#if !NETCF
+ private readonly WorkShift _nonParallelSTAShift = new WorkShift("NonParallelSTA");
+ private readonly Lazy<WorkItemQueue> _parallelSTAQueue;
+ private readonly Lazy<WorkItemQueue> _nonParallelSTAQueue;
+#endif
+
+ // The first WorkItem to be dispatched, assumed to be top-level item
+ private WorkItem _topLevelWorkItem;
+
+ /// <summary>
+ /// Construct a ParallelWorkItemDispatcher
+ /// </summary>
+ /// <param name="levelOfParallelism">Number of workers to use</param>
+ public ParallelWorkItemDispatcher(int levelOfParallelism)
+ {
+ _levelOfParallelism = levelOfParallelism;
+
+ Shifts = new WorkShift[]
+ {
+ _parallelShift,
+ _nonParallelShift,
+#if !NETCF
+ _nonParallelSTAShift
+#endif
+ };
+ foreach (var shift in Shifts)
+ shift.EndOfShift += OnEndOfShift;
+
+ _parallelQueue = new Lazy<WorkItemQueue>(() =>
+ {
+ var parallelQueue = new WorkItemQueue("ParallelQueue");
+ _parallelShift.AddQueue(parallelQueue);
+
+ for (int i = 1; i <= _levelOfParallelism; i++)
+ {
+ string name = string.Format("Worker#" + i.ToString());
+#if NETCF
+ _parallelShift.Assign(new TestWorker(parallelQueue, name));
+#else
+ _parallelShift.Assign(new TestWorker(parallelQueue, name, ApartmentState.MTA));
+#endif
+ }
+
+ return parallelQueue;
+ });
+
+#if !NETCF
+ _parallelSTAQueue = new Lazy<WorkItemQueue>(() =>
+ {
+ var parallelSTAQueue = new WorkItemQueue("ParallelSTAQueue");
+ _parallelShift.AddQueue(parallelSTAQueue);
+ _parallelShift.Assign(new TestWorker(parallelSTAQueue, "Worker#STA", ApartmentState.STA));
+
+ return parallelSTAQueue;
+ });
+#endif
+
+ _nonParallelQueue = new Lazy<WorkItemQueue>(() =>
+ {
+ var nonParallelQueue = new WorkItemQueue("NonParallelQueue");
+ _nonParallelShift.AddQueue(nonParallelQueue);
+#if NETCF
+ _nonParallelShift.Assign(new TestWorker(nonParallelQueue, "Worker#NP"));
+#else
+ _nonParallelShift.Assign(new TestWorker(nonParallelQueue, "Worker#STA_NP", ApartmentState.MTA));
+#endif
+
+ return nonParallelQueue;
+ });
+
+#if !NETCF
+ _nonParallelSTAQueue = new Lazy<WorkItemQueue>(() =>
+ {
+ var nonParallelSTAQueue = new WorkItemQueue("NonParallelSTAQueue");
+ _nonParallelSTAShift.AddQueue(nonParallelSTAQueue);
+ _nonParallelSTAShift.Assign(new TestWorker(nonParallelSTAQueue, "Worker#NP_STA", ApartmentState.STA));
+
+ return nonParallelSTAQueue;
+ });
+#endif
+ }
+
+ /// <summary>
+ /// Enumerates all the shifts supported by the dispatcher
+ /// </summary>
+ public IEnumerable<WorkShift> Shifts { get; private set; }
+
+ #region IWorkItemDispatcher Members
+
+ /// <summary>
+ /// Dispatch a single work item for execution. The first
+ /// work item dispatched is saved as the top-level
+ /// work item and used when stopping the run.
+ /// </summary>
+ /// <param name="work">The item to dispatch</param>
+ public void Dispatch(WorkItem work)
+ {
+ // Special handling of the top-level item
+ if (Interlocked.CompareExchange (ref _topLevelWorkItem, work, null) == null)
+ {
+ Enqueue(work);
+ StartNextShift();
+ }
+ // We run child items directly, rather than enqueuing them...
+ // 1. If the context is single threaded.
+ // 2. If there is no fixture, and so nothing to do but dispatch grandchildren.
+ // 3. For now, if this represents a test case. This avoids issues of
+ // tests that access the fixture state and allows handling ApartmentState
+ // preferences set on the fixture.
+ else if (work.Context.IsSingleThreaded
+ || work.Test.TypeInfo == null
+ || work is SimpleWorkItem)
+ Execute(work);
+ else
+ Enqueue(work);
+
+ Interlocked.Increment(ref _itemsDispatched);
+ }
+
+ private void Execute(WorkItem work)
+ {
+ log.Debug("Directly executing {0}", work.Test.Name);
+ work.Execute();
+ }
+
+ private void Enqueue(WorkItem work)
+ {
+ log.Debug("Enqueuing {0}", work.Test.Name);
+
+ if (work.IsParallelizable)
+ {
+#if !NETCF
+ if (work.TargetApartment == ApartmentState.STA)
+ ParallelSTAQueue.Enqueue(work);
+ else
+#endif
+ ParallelQueue.Enqueue(work);
+ }
+#if !NETCF
+ else if (work.TargetApartment == ApartmentState.STA)
+ NonParallelSTAQueue.Enqueue(work);
+#endif
+ else
+ NonParallelQueue.Enqueue(work);
+ }
+
+ /// <summary>
+ /// Cancel the ongoing run completely.
+ /// If no run is in process, the call has no effect.
+ /// </summary>
+ public void CancelRun(bool force)
+ {
+ foreach (var shift in Shifts)
+ shift.Cancel(force);
+ }
+
+ #endregion
+
+ #region Private Queue Properties
+
+ // Queues are not actually created until the first time the property
+ // is referenced by the Dispatch method adding a WorkItem to it.
+
+ private WorkItemQueue ParallelQueue
+ {
+ get
+ {
+ return _parallelQueue.Value;
+ }
+ }
+
+#if !NETCF
+ private WorkItemQueue ParallelSTAQueue
+ {
+ get
+ {
+ return _parallelSTAQueue.Value;
+ }
+ }
+#endif
+
+ private WorkItemQueue NonParallelQueue
+ {
+ get
+ {
+ return _nonParallelQueue.Value;
+ }
+ }
+
+#if !NETCF
+ private WorkItemQueue NonParallelSTAQueue
+ {
+ get
+ {
+ return _nonParallelSTAQueue.Value;
+ }
+ }
+#endif
+ #endregion
+
+ #region Helper Methods
+
+ private void OnEndOfShift(object sender, EventArgs ea)
+ {
+ if (!StartNextShift())
+ {
+ foreach (var shift in Shifts)
+ shift.ShutDown();
+ }
+ }
+
+ private bool StartNextShift()
+ {
+ foreach (var shift in Shifts)
+ {
+ if (shift.HasWork)
+ {
+ shift.Start();
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ #endregion
+ }
+}
+
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// QueuingEventListener uses an EventQueue to store any
+ /// events received on its EventListener interface.
+ /// </summary>
+ public class QueuingEventListener : ITestListener
+ {
+ /// <summary>
+ /// The EventQueue created and filled by this listener
+ /// </summary>
+ public EventQueue Events { get; private set; }
+
+ /// <summary>
+ /// Construct a QueuingEventListener
+ /// </summary>
+ public QueuingEventListener()
+ {
+ Events = new EventQueue();
+ }
+
+ #region EventListener Methods
+ /// <summary>
+ /// A test has started
+ /// </summary>
+ /// <param name="test">The test that is starting</param>
+ public void TestStarted(ITest test)
+ {
+ Events.Enqueue( new TestStartedEvent( test ) );
+ }
+
+ /// <summary>
+ /// A test case finished
+ /// </summary>
+ /// <param name="result">Result of the test case</param>
+ public void TestFinished(ITestResult result)
+ {
+ Events.Enqueue( new TestFinishedEvent( result ) );
+ }
+
+ /// <summary>
+ /// Called when a test produces output for immediate display
+ /// </summary>
+ /// <param name="output">A TestOutput object containing the text to display</param>
+ public void TestOutput(TestOutput output)
+ {
+ Events.Enqueue(new TestOutputEvent(output));
+ }
+
+ #endregion
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Threading;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal.Commands;
+using NUnit.Framework.TUnit;
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// A SimpleWorkItem represents a single test case and is
+ /// marked as completed immediately upon execution. This
+ /// class is also used for skipped or ignored test suites.
+ /// </summary>
+ public class SimpleWorkItem : WorkItem
+ {
+ private TestCommand _command;
+
+ /// <summary>
+ /// Construct a simple work item for a test.
+ /// </summary>
+ /// <param name="test">The test to be executed</param>
+ /// <param name="filter">The filter used to select this test</param>
+ public SimpleWorkItem(TestMethod test, ITestFilter filter) : base(test)
+ {
+ _command = test.RunState == RunState.Runnable || test.RunState == RunState.Explicit && filter.IsExplicitMatch(test)
+ ? CommandBuilder.MakeTestCommand(test)
+ : CommandBuilder.MakeSkipCommand(test);
+ }
+
+ /// <summary>
+ /// Method that performs actually performs the work.
+ /// </summary>
+ protected override void PerformWork()
+ {
+ try
+ {
+ Result = _command.Execute(Context);
+ // [DuongNT]: Write out the method's results
+ if (!TSettings.GetInstance().IsSlaveMode && !TSettings.GetInstance().IsManual)
+ {
+ TLogger.Write("##### Result of ["+ Result.FullName + "] TC : " + Result.ResultState.ToString());
+ }
+ }
+ finally
+ {
+ WorkItemComplete();
+ }
+ }
+
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Threading;
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// SimpleWorkItemDispatcher handles execution of WorkItems by
+ /// directly executing them. It is provided so that a dispatcher
+ /// is always available in the context, thereby simplifying the
+ /// code needed to run child tests.
+ /// </summary>
+ public class SimpleWorkItemDispatcher : IWorkItemDispatcher
+ {
+#if !PORTABLE
+ // The first WorkItem to be dispatched, assumed to be top-level item
+ private WorkItem _topLevelWorkItem;
+
+ // Thread used to run and cancel tests
+ private Thread _runnerThread;
+#endif
+
+ #region IWorkItemDispatcher Members
+
+ /// <summary>
+ /// Dispatch a single work item for execution. The first
+ /// work item dispatched is saved as the top-level
+ /// work item and a thread is created on which to
+ /// run it. Subsequent calls come from the top level
+ /// item or its descendants on the proper thread.
+ /// </summary>
+ /// <param name="work">The item to dispatch</param>
+ public void Dispatch(WorkItem work)
+ {
+#if PORTABLE
+ if (work != null)
+ work.Execute();
+#else
+ if (_topLevelWorkItem != null)
+ work.Execute();
+ else
+ {
+ _topLevelWorkItem = work;
+ _runnerThread = new Thread(RunnerThreadProc);
+
+#if !NETCF && !SILVERLIGHT
+ if (work.TargetApartment == ApartmentState.STA)
+ _runnerThread.SetApartmentState(ApartmentState.STA);
+#endif
+
+ _runnerThread.Start();
+ }
+#endif
+ }
+
+#if !PORTABLE
+ private void RunnerThreadProc()
+ {
+ _topLevelWorkItem.Execute();
+ }
+#endif
+
+#if !PORTABLE
+ private object cancelLock = new object();
+#endif
+
+ /// <summary>
+ /// Cancel (abort or stop) the ongoing run.
+ /// If no run is in process, the call has no effect.
+ /// </summary>
+ /// <param name="force">true if the run should be aborted, false if it should allow its currently running test to complete</param>
+ public void CancelRun(bool force)
+ {
+#if !PORTABLE
+ lock (cancelLock)
+ {
+ if (_topLevelWorkItem != null)
+ {
+ _topLevelWorkItem.Cancel(force);
+ if (force)
+ _topLevelWorkItem = null;
+ }
+ }
+#endif
+ }
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#define NETCF
+#if PARALLEL
+using System;
+using System.Threading;
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// A TestWorker pulls work items from a queue
+ /// and executes them.
+ /// </summary>
+ public class TestWorker
+ {
+ private static Logger log = InternalTrace.GetLogger("TestWorker");
+
+ private WorkItemQueue _readyQueue;
+ private Thread _workerThread;
+
+ private int _workItemCount = 0;
+
+ private bool _running;
+
+ /// <summary>
+ /// Event signaled immediately before executing a WorkItem
+ /// </summary>
+ public event EventHandler Busy;
+
+ /// <summary>
+ /// Event signaled immediately after executing a WorkItem
+ /// </summary>
+ public event EventHandler Idle;
+
+#if NETCF
+ /// <summary>
+ /// Construct a new TestWorker.
+ /// </summary>
+ /// <param name="queue">The queue from which to pull work items</param>
+ /// <param name="name">The name of this worker</param>
+ public TestWorker(WorkItemQueue queue, string name)
+#else
+ /// <summary>
+ /// Construct a new TestWorker.
+ /// </summary>
+ /// <param name="queue">The queue from which to pull work items</param>
+ /// <param name="name">The name of this worker</param>
+ /// <param name="apartmentState">The apartment state to use for running tests</param>
+ public TestWorker(WorkItemQueue queue, string name, ApartmentState apartmentState)
+#endif
+ {
+ _readyQueue = queue;
+
+ _workerThread = new Thread(new ThreadStart(TestWorkerThreadProc));
+ _workerThread.Name = name;
+#if !NETCF
+ _workerThread.SetApartmentState(apartmentState);
+#endif
+ }
+
+ /// <summary>
+ /// The name of this worker - also used for the thread
+ /// </summary>
+ public string Name
+ {
+ get { return _workerThread.Name; }
+ }
+
+ /// <summary>
+ /// Indicates whether the worker thread is running
+ /// </summary>
+ public bool IsAlive
+ {
+#if NETCF
+ get { return !_workerThread.Join(0); }
+#else
+ get { return _workerThread.IsAlive; }
+#endif
+ }
+
+ /// <summary>
+ /// Our ThreadProc, which pulls and runs tests in a loop
+ /// </summary>
+ private WorkItem _currentWorkItem;
+
+ private void TestWorkerThreadProc()
+ {
+ log.Info("{0} starting ", _workerThread.Name);
+
+ _running = true;
+
+ try
+ {
+ while (_running)
+ {
+ _currentWorkItem = _readyQueue.Dequeue();
+ if (_currentWorkItem == null)
+ break;
+
+ log.Info("{0} executing {1}", _workerThread.Name, _currentWorkItem.Test.Name);
+
+ if (Busy != null)
+ Busy(this, EventArgs.Empty);
+
+ _currentWorkItem.WorkerId = Name;
+ _currentWorkItem.Execute();
+
+ if (Idle != null)
+ Idle(this, EventArgs.Empty);
+
+ ++_workItemCount;
+ }
+ }
+ finally
+ {
+ log.Info("{0} stopping - {1} WorkItems processed.", _workerThread.Name, _workItemCount);
+ }
+ }
+
+ /// <summary>
+ /// Start processing work items.
+ /// </summary>
+ public void Start()
+ {
+ _workerThread.Start();
+ }
+
+ private object cancelLock = new object();
+
+ /// <summary>
+ /// Stop the thread, either immediately or after finishing the current WorkItem
+ /// </summary>
+ /// <param name="force">true if the thread should be aborted, false if it should allow the currently running test to complete</param>
+ public void Cancel(bool force)
+ {
+ if (force)
+ _running = false;
+
+ lock (cancelLock)
+ if (_workerThread != null && _currentWorkItem != null)
+ {
+ _currentWorkItem.Cancel(force);
+ if (force)
+ _currentWorkItem = null;
+ }
+ }
+ }
+}
+
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !SILVERLIGHT && !NETCF && !PORTABLE
+using System;
+using System.IO;
+//using System.Runtime.Remoting.Messaging;
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// The TextCapture class intercepts console output and writes it
+ /// to the current execution context, if one is present on the thread.
+ /// If no execution context is found, the output is written to a
+ /// default destination, normally the original destination of the
+ /// intercepted output.
+ /// </summary>
+ public class TextCapture : TextWriter
+ {
+ private TextWriter _defaultWriter;
+
+ /// <summary>
+ /// Construct a TextCapture object
+ /// </summary>
+ /// <param name="defaultWriter">The default destination for non-intercepted output</param>
+ public TextCapture(TextWriter defaultWriter)
+ {
+ _defaultWriter = defaultWriter;
+ }
+
+ /// <summary>
+ /// Gets the Encoding in use by this TextWriter
+ /// </summary>
+ public override System.Text.Encoding Encoding
+ {
+ get { return _defaultWriter.Encoding; }
+ }
+
+ /// <summary>
+ /// Writes a single character
+ /// </summary>
+ /// <param name="value">The char to write</param>
+ public override void Write(char value)
+ {
+ var context = TestExecutionContext.GetTestExecutionContext();
+
+ if (context != null && context.CurrentResult != null)
+ context.CurrentResult.OutWriter.Write(value);
+ else
+ _defaultWriter.Write(value);
+ }
+
+ /// <summary>
+ /// Writes a string
+ /// </summary>
+ /// <param name="value">The string to write</param>
+ public override void Write(string value)
+ {
+ var context = TestExecutionContext.GetTestExecutionContext();
+
+ if (context != null && context.CurrentResult != null)
+ context.CurrentResult.OutWriter.Write(value);
+ else
+ _defaultWriter.Write(value);
+ }
+
+ /// <summary>
+ /// Writes a string followed by a line terminator
+ /// </summary>
+ /// <param name="value">The string to write</param>
+ public override void WriteLine(string value)
+ {
+ var context = TestExecutionContext.GetTestExecutionContext();
+
+ if (context != null && context.CurrentResult != null)
+ context.CurrentResult.OutWriter.WriteLine(value);
+ else
+ _defaultWriter.WriteLine(value);
+ }
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Globalization;
+using NUnit.Framework.Constraints;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// TextMessageWriter writes constraint descriptions and messages
+ /// in displayable form as a text stream. It tailors the display
+ /// of individual message components to form the standard message
+ /// format of NUnit assertion failure messages.
+ /// </summary>
+ public class TextMessageWriter : MessageWriter
+ {
+ #region Message Formats and Constants
+ private static readonly int DEFAULT_LINE_LENGTH = 78;
+
+ // Prefixes used in all failure messages. All must be the same
+ // length, which is held in the PrefixLength field. Should not
+ // contain any tabs or newline characters.
+ /// <summary>
+ /// Prefix used for the expected value line of a message
+ /// </summary>
+ public static readonly string Pfx_Expected = " Expected: ";
+ /// <summary>
+ /// Prefix used for the actual value line of a message
+ /// </summary>
+ public static readonly string Pfx_Actual = " But was: ";
+ /// <summary>
+ /// Length of a message prefix
+ /// </summary>
+ public static readonly int PrefixLength = Pfx_Expected.Length;
+
+ #endregion
+
+ private int maxLineLength = DEFAULT_LINE_LENGTH;
+
+ #region Constructors
+ /// <summary>
+ /// Construct a TextMessageWriter
+ /// </summary>
+ public TextMessageWriter() { }
+
+ /// <summary>
+ /// Construct a TextMessageWriter, specifying a user message
+ /// and optional formatting arguments.
+ /// </summary>
+ /// <param name="userMessage"></param>
+ /// <param name="args"></param>
+ public TextMessageWriter(string userMessage, params object[] args)
+ {
+ if ( userMessage != null && userMessage != string.Empty)
+ this.WriteMessageLine(userMessage, args);
+ }
+ #endregion
+
+ #region Properties
+ /// <summary>
+ /// Gets or sets the maximum line length for this writer
+ /// </summary>
+ public override int MaxLineLength
+ {
+ get { return maxLineLength; }
+ set { maxLineLength = value; }
+ }
+ #endregion
+
+ #region Public Methods - High Level
+ /// <summary>
+ /// Method to write single line message with optional args, usually
+ /// written to precede the general failure message, at a given
+ /// indentation level.
+ /// </summary>
+ /// <param name="level">The indentation level of the message</param>
+ /// <param name="message">The message to be written</param>
+ /// <param name="args">Any arguments used in formatting the message</param>
+ public override void WriteMessageLine(int level, string message, params object[] args)
+ {
+ if (message != null)
+ {
+ while (level-- >= 0) Write(" ");
+
+ if (args != null && args.Length > 0)
+ message = string.Format(message, args);
+
+ WriteLine(MsgUtils.EscapeControlChars(message));
+ }
+ }
+
+ /// <summary>
+ /// Display Expected and Actual lines for a constraint. This
+ /// is called by MessageWriter's default implementation of
+ /// WriteMessageTo and provides the generic two-line display.
+ /// </summary>
+ /// <param name="result">The result of the constraint that failed</param>
+ public override void DisplayDifferences(ConstraintResult result)
+ {
+ WriteExpectedLine(result);
+ WriteActualLine(result);
+ }
+
+ /// <summary>
+ /// Display Expected and Actual lines for given _values. This
+ /// method may be called by constraints that need more control over
+ /// the display of actual and expected _values than is provided
+ /// by the default implementation.
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ /// <param name="actual">The actual value causing the failure</param>
+ public override void DisplayDifferences(object expected, object actual)
+ {
+ WriteExpectedLine(expected);
+ WriteActualLine(actual);
+ }
+
+ /// <summary>
+ /// Display Expected and Actual lines for given _values, including
+ /// a tolerance value on the expected line.
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ /// <param name="actual">The actual value causing the failure</param>
+ /// <param name="tolerance">The tolerance within which the test was made</param>
+ public override void DisplayDifferences(object expected, object actual, Tolerance tolerance)
+ {
+ WriteExpectedLine(expected, tolerance);
+ WriteActualLine(actual);
+ }
+
+ /// <summary>
+ /// Display the expected and actual string _values on separate lines.
+ /// If the mismatch parameter is >=0, an additional line is displayed
+ /// line containing a caret that points to the mismatch point.
+ /// </summary>
+ /// <param name="expected">The expected string value</param>
+ /// <param name="actual">The actual string value</param>
+ /// <param name="mismatch">The point at which the strings don't match or -1</param>
+ /// <param name="ignoreCase">If true, case is ignored in string comparisons</param>
+ /// <param name="clipping">If true, clip the strings to fit the max line length</param>
+ public override void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping)
+ {
+ // Maximum string we can display without truncating
+ int maxDisplayLength = MaxLineLength
+ - PrefixLength // Allow for prefix
+ - 2; // 2 quotation marks
+
+ if ( clipping )
+ MsgUtils.ClipExpectedAndActual(ref expected, ref actual, maxDisplayLength, mismatch);
+
+ expected = MsgUtils.EscapeControlChars(expected);
+ actual = MsgUtils.EscapeControlChars(actual);
+
+ // The mismatch position may have changed due to clipping or white space conversion
+ mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, ignoreCase);
+
+ Write( Pfx_Expected );
+ Write( MsgUtils.FormatValue(expected) );
+ if ( ignoreCase )
+ Write( ", ignoring case" );
+ WriteLine();
+ WriteActualLine( actual );
+ //DisplayDifferences(expected, actual);
+ if (mismatch >= 0)
+ WriteCaretLine(mismatch);
+ }
+ #endregion
+
+ #region Public Methods - Low Level
+
+ /// <summary>
+ /// Writes the text for an actual value.
+ /// </summary>
+ /// <param name="actual">The actual value.</param>
+ public override void WriteActualValue(object actual)
+ {
+ WriteValue(actual);
+ }
+
+ /// <summary>
+ /// Writes the text for a generalized value.
+ /// </summary>
+ /// <param name="val">The value.</param>
+ public override void WriteValue(object val)
+ {
+ Write(MsgUtils.FormatValue(val));
+ }
+
+ /// <summary>
+ /// Writes the text for a collection value,
+ /// starting at a particular point, to a max length
+ /// </summary>
+ /// <param name="collection">The collection containing elements to write.</param>
+ /// <param name="start">The starting point of the elements to write</param>
+ /// <param name="max">The maximum number of elements to write</param>
+ public override void WriteCollectionElements(IEnumerable collection, long start, int max)
+ {
+ Write(MsgUtils.FormatCollection(collection, start, max));
+ }
+
+ #endregion
+
+ #region Helper Methods
+ /// <summary>
+ /// Write the generic 'Expected' line for a constraint
+ /// </summary>
+ /// <param name="result">The constraint that failed</param>
+ private void WriteExpectedLine(ConstraintResult result)
+ {
+ Write(Pfx_Expected);
+ WriteLine(result.Description);
+ }
+
+ /// <summary>
+ /// Write the generic 'Expected' line for a given value
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ private void WriteExpectedLine(object expected)
+ {
+ WriteExpectedLine(expected, null);
+ }
+
+ /// <summary>
+ /// Write the generic 'Expected' line for a given value
+ /// and tolerance.
+ /// </summary>
+ /// <param name="expected">The expected value</param>
+ /// <param name="tolerance">The tolerance within which the test was made</param>
+ private void WriteExpectedLine(object expected, Tolerance tolerance)
+ {
+ Write(Pfx_Expected);
+ Write(MsgUtils.FormatValue(expected));
+
+ if (tolerance != null && !tolerance.IsUnsetOrDefault)
+ {
+ Write(" +/- ");
+ Write(MsgUtils.FormatValue(tolerance.Value));
+ if (tolerance.Mode != ToleranceMode.Linear)
+ Write(" {0}", tolerance.Mode);
+ }
+
+ WriteLine();
+ }
+
+ /// <summary>
+ /// Write the generic 'Actual' line for a constraint
+ /// </summary>
+ /// <param name="result">The ConstraintResult for which the actual value is to be written</param>
+ private void WriteActualLine(ConstraintResult result)
+ {
+ Write(Pfx_Actual);
+ result.WriteActualValueTo(this);
+ WriteLine();
+ //WriteLine(MsgUtils.FormatValue(result.ActualValue));
+ }
+
+ /// <summary>
+ /// Write the generic 'Actual' line for a given value
+ /// </summary>
+ /// <param name="actual">The actual value causing a failure</param>
+ private void WriteActualLine(object actual)
+ {
+ Write(Pfx_Actual);
+ WriteActualValue(actual);
+ WriteLine();
+ }
+
+ private void WriteCaretLine(int mismatch)
+ {
+ // We subtract 2 for the initial 2 blanks and add back 1 for the initial quote
+ WriteLine(" {0}^", new string('-', PrefixLength + mismatch - 2 + 1));
+ }
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Threading;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// A WorkItem may be an individual test case, a fixture or
+ /// a higher level grouping of tests. All WorkItems inherit
+ /// from the abstract WorkItem class, which uses the template
+ /// pattern to allow derived classes to perform work in
+ /// whatever way is needed.
+ ///
+ /// A WorkItem is created with a particular TestExecutionContext
+ /// and is responsible for re-establishing that context in the
+ /// current thread before it begins or resumes execution.
+ /// </summary>
+ public abstract class WorkItem
+ {
+ static Logger log = InternalTrace.GetLogger("WorkItem");
+
+ #region Static Factory Method
+
+ /// <summary>
+ /// Creates a work item.
+ /// </summary>
+ /// <param name="test">The test for which this WorkItem is being created.</param>
+ /// <param name="filter">The filter to be used in selecting any child Tests.</param>
+ /// <returns></returns>
+ static public WorkItem CreateWorkItem(ITest test, ITestFilter filter)
+ {
+ TestSuite suite = test as TestSuite;
+ if (suite != null)
+ return new CompositeWorkItem(suite, filter);
+ else
+ return new SimpleWorkItem((TestMethod)test, filter);
+ }
+
+ #endregion
+
+ #region Construction and Initialization
+
+ /// <summary>
+ /// Construct a WorkItem for a particular test.
+ /// </summary>
+ /// <param name="test">The test that the WorkItem will run</param>
+ public WorkItem(Test test)
+ {
+ Test = test;
+ Result = test.MakeTestResult();
+ State = WorkItemState.Ready;
+ Actions = new List<ITestAction>();
+#if !PORTABLE && !SILVERLIGHT && !NETCF
+ TargetApartment = Test.Properties.ContainsKey(PropertyNames.ApartmentState)
+ ? (ApartmentState)Test.Properties.Get(PropertyNames.ApartmentState)
+ : ApartmentState.Unknown;
+#endif
+ }
+
+ /// <summary>
+ /// Initialize the TestExecutionContext. This must be done
+ /// before executing the WorkItem.
+ /// </summary>
+ /// <remarks>
+ /// Originally, the context was provided in the constructor
+ /// but delaying initialization of the context until the item
+ /// is about to be dispatched allows changes in the parent
+ /// context during OneTimeSetUp to be reflected in the child.
+ /// </remarks>
+ /// <param name="context">The TestExecutionContext to use</param>
+ public void InitializeContext(TestExecutionContext context)
+ {
+ Guard.OperationValid(Context == null, "The context has already been initialized");
+
+ Context = context;
+
+ //if (Test is TestAssembly)
+ // Actions.AddRange(ActionsHelper.GetActionsFromAttributeProvider(((TestAssembly)Test).Assembly));
+ //else if (Test is ParameterizedMethodSuite)
+ // Actions.AddRange(ActionsHelper.GetActionsFromAttributeProvider(Test.Method.MethodInfo));
+ //else if (Test.TypeInfo != null)
+ // Actions.AddRange(ActionsHelper.GetActionsFromTypesAttributes(Test.TypeInfo.Type));
+ }
+
+ #endregion
+
+ #region Properties and Events
+
+ /// <summary>
+ /// Event triggered when the item is complete
+ /// </summary>
+ public event EventHandler Completed;
+
+ /// <summary>
+ /// Gets the current state of the WorkItem
+ /// </summary>
+ public WorkItemState State { get; private set; }
+
+ /// <summary>
+ /// The test being executed by the work item
+ /// </summary>
+ public Test Test { get; private set; }
+
+ /// <summary>
+ /// The execution context
+ /// </summary>
+ public TestExecutionContext Context { get; private set; }
+
+ /// <summary>
+ /// The unique id of the worker executing this item.
+ /// </summary>
+ public string WorkerId {get; internal set;}
+
+ /// <summary>
+ /// The test actions to be performed before and after this test
+ /// </summary>
+ public List<ITestAction> Actions { get; private set; }
+
+#if PARALLEL
+ /// <summary>
+ /// Indicates whether this WorkItem may be run in parallel
+ /// </summary>
+ public bool IsParallelizable
+ {
+ get
+ {
+ ParallelScope scope = ParallelScope.None;
+
+ if (Test.Properties.ContainsKey(PropertyNames.ParallelScope))
+ {
+ scope = (ParallelScope)Test.Properties.Get(PropertyNames.ParallelScope);
+
+ if ((scope & ParallelScope.Self) != 0)
+ return true;
+ }
+ else
+ {
+ scope = Context.ParallelScope;
+
+ if ((scope & ParallelScope.Children) != 0)
+ return true;
+ }
+
+ if (Test is TestFixture && (scope & ParallelScope.Fixtures) != 0)
+ return true;
+
+ // Special handling for the top level TestAssembly.
+ // If it has any scope specified other than None,
+ // we will use the parallel queue. This heuristic
+ // is intended to minimize creation of unneeded
+ // queues and workers, since the assembly and
+ // namespace level tests can easily run in any queue.
+ if (Test is TestAssembly && scope != ParallelScope.None)
+ return true;
+
+ return false;
+ }
+ }
+#endif
+
+ /// <summary>
+ /// The test result
+ /// </summary>
+ public TestResult Result { get; protected set; }
+
+#if !SILVERLIGHT && !NETCF && !PORTABLE
+ internal ApartmentState TargetApartment { get; set; }
+ private ApartmentState CurrentApartment { get; set; }
+#endif
+
+ #endregion
+
+ #region OwnThreadReason Enumeration
+
+ [Flags]
+ private enum OwnThreadReason
+ {
+ NotNeeded = 0,
+ RequiresThread = 1,
+ Timeout = 2,
+ DifferentApartment = 4
+ }
+
+ #endregion
+
+ #region Public Methods
+
+ /// <summary>
+ /// Execute the current work item, including any
+ /// child work items.
+ /// </summary>
+ public virtual void Execute()
+ {
+ // Timeout set at a higher level
+ int timeout = Context.TestCaseTimeout;
+
+ // Timeout set on this test
+ if (Test.Properties.ContainsKey(PropertyNames.Timeout))
+ timeout = (int)Test.Properties.Get(PropertyNames.Timeout);
+
+ // Unless the context is single threaded, a supplementary thread
+ // is created on the various platforms...
+ // 1. If the test used the RequiresThreadAttribute.
+ // 2. If a test method has a timeout.
+ // 3. If the test needs to run in a different apartment.
+ //
+ // NOTE: We want to eliminate or significantly reduce
+ // cases 2 and 3 in the future.
+ //
+ // Case 2 requires the ability to stop and start test workers
+ // dynamically. We would cancel the worker thread, dispose of
+ // the worker and start a new worker on a new thread.
+ //
+ // Case 3 occurs when using either dispatcher whenever a
+ // child test calls for a different apartment from the one
+ // used by it's parent. It routinely occurs under the simple
+ // dispatcher (--workers=0 option). Under the parallel dispatcher
+ // it is needed when test cases are not enabled for parallel
+ // execution. Currently, test cases are always run sequentially,
+ // so this continues to apply fairly generally.
+
+ var ownThreadReason = OwnThreadReason.NotNeeded;
+
+#if !PORTABLE
+ if (Test.RequiresThread)
+ ownThreadReason |= OwnThreadReason.RequiresThread;
+ if (timeout > 0 && Test is TestMethod)
+ ownThreadReason |= OwnThreadReason.Timeout;
+#if !SILVERLIGHT && !NETCF
+ CurrentApartment = Thread.CurrentThread.GetApartmentState();
+ if (CurrentApartment != TargetApartment && TargetApartment != ApartmentState.Unknown)
+ ownThreadReason |= OwnThreadReason.DifferentApartment;
+#endif
+#endif
+
+ if (ownThreadReason == OwnThreadReason.NotNeeded)
+ RunTest();
+ else if (Context.IsSingleThreaded)
+ {
+ var msg = "Test is not runnable in single-threaded context. " + ownThreadReason;
+ log.Error(msg);
+ Result.SetResult(ResultState.NotRunnable, msg);
+ WorkItemComplete();
+ }
+ else
+ {
+ log.Debug("Running test on own thread. " + ownThreadReason);
+#if SILVERLIGHT || NETCF
+ RunTestOnOwnThread(timeout);
+#elif !PORTABLE
+ var apartment = (ownThreadReason | OwnThreadReason.DifferentApartment) != 0
+ ? TargetApartment
+ : CurrentApartment;
+ RunTestOnOwnThread(timeout, apartment);
+#endif
+ }
+ }
+
+#if SILVERLIGHT || NETCF
+ private Thread thread;
+
+ private void RunTestOnOwnThread(int timeout)
+ {
+ thread = new Thread(RunTest);
+ RunThread(timeout);
+ }
+#endif
+
+#if !SILVERLIGHT && !NETCF && !PORTABLE
+ private Thread thread;
+
+ private void RunTestOnOwnThread(int timeout, ApartmentState apartment)
+ {
+ thread = new Thread(new ThreadStart(RunTest));
+ thread.SetApartmentState(apartment);
+ RunThread(timeout);
+ }
+#endif
+
+#if !PORTABLE
+ private void RunThread(int timeout)
+ {
+#if !NETCF
+ thread.CurrentCulture = Context.CurrentCulture;
+ thread.CurrentUICulture = Context.CurrentUICulture;
+#endif
+
+ thread.Start();
+
+ if (!Test.IsAsynchronous || timeout > 0)
+ {
+ if (timeout <= 0)
+ timeout = Timeout.Infinite;
+
+ if (!thread.Join(timeout))
+ {
+ Thread tThread;
+ lock (threadLock)
+ {
+ if (thread == null)
+ return;
+
+ tThread = thread;
+ thread = null;
+ }
+
+ if (Context.ExecutionStatus == TestExecutionStatus.AbortRequested)
+ return;
+
+ log.Debug("Killing thread {0}, which exceeded timeout", tThread.ManagedThreadId);
+ ThreadUtility.Kill(tThread);
+
+ // NOTE: Without the use of Join, there is a race condition here.
+ // The thread sets the result to Cancelled and our code below sets
+ // it to Failure. In order for the result to be shown as a failure,
+ // we need to ensure that the following code executes after the
+ // thread has terminated. There is a risk here: the test code might
+ // refuse to terminate. However, it's more important to deal with
+ // the normal rather than a pathological case.
+ tThread.Join();
+
+ log.Debug("Changing result from {0} to Timeout Failure", Result.ResultState);
+
+ Result.SetResult(ResultState.Failure,
+ string.Format("Test exceeded Timeout value of {0}ms", timeout));
+
+ WorkItemComplete();
+ }
+ }
+ }
+#endif
+
+ private void RunTest()
+ {
+ Context.CurrentTest = this.Test;
+ Context.CurrentResult = this.Result;
+ Context.Listener.TestStarted(this.Test);
+ Context.StartTime = DateTime.UtcNow;
+ Context.StartTicks = Stopwatch.GetTimestamp();
+ Context.WorkerId = this.WorkerId;
+ Context.EstablishExecutionEnvironment();
+
+ State = WorkItemState.Running;
+
+ PerformWork();
+ }
+
+ private object threadLock = new object();
+
+ /// <summary>
+ /// Cancel (abort or stop) a WorkItem
+ /// </summary>
+ /// <param name="force">true if the WorkItem should be aborted, false if it should run to completion</param>
+ public virtual void Cancel(bool force)
+ {
+ if (Context != null)
+ Context.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested;
+
+ if (!force)
+ return;
+
+#if !PORTABLE
+ Thread tThread;
+
+ lock (threadLock)
+ {
+ if (thread == null)
+ return;
+
+ tThread = thread;
+ thread = null;
+ }
+
+ if (!tThread.Join(0))
+ {
+ log.Debug("Killing thread {0} for cancel", tThread.ManagedThreadId);
+ ThreadUtility.Kill(tThread);
+
+ tThread.Join();
+
+ log.Debug("Changing result from {0} to Cancelled", Result.ResultState);
+
+ Result.SetResult(ResultState.Cancelled, "Cancelled by user");
+
+ WorkItemComplete();
+ }
+#endif
+ }
+
+#endregion
+
+#region Protected Methods
+
+ /// <summary>
+ /// Method that performs actually performs the work. It should
+ /// set the State to WorkItemState.Complete when done.
+ /// </summary>
+ protected abstract void PerformWork();
+
+ /// <summary>
+ /// Method called by the derived class when all work is complete
+ /// </summary>
+ protected void WorkItemComplete()
+ {
+ State = WorkItemState.Complete;
+
+ Result.StartTime = Context.StartTime;
+ Result.EndTime = DateTime.UtcNow;
+
+ long tickCount = Stopwatch.GetTimestamp() - Context.StartTicks;
+ double seconds = (double)tickCount / Stopwatch.Frequency;
+ Result.Duration = seconds;
+
+ // We add in the assert count from the context. If
+ // this item is for a test case, we are adding the
+ // test assert count to zero. If it's a fixture, we
+ // are adding in any asserts that were run in the
+ // fixture setup or teardown. Each context only
+ // counts the asserts taking place in that context.
+ // Each result accumulates the count from child
+ // results along with it's own asserts.
+ Result.AssertCount += Context.AssertCount;
+
+ Context.Listener.TestFinished(Result);
+
+ if (Completed != null)
+ Completed(this, EventArgs.Empty);
+
+ //Clear references to test objects to reduce memory usage
+ Context.TestObject = null;
+ Test.Fixture = null;
+ }
+
+#endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if PARALLEL
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Threading;
+#if NET_2_0 || NET_3_5 || NETCF
+using ManualResetEventSlim = System.Threading.ManualResetEvent;
+#endif
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// WorkItemQueueState indicates the current state of a WorkItemQueue
+ /// </summary>
+ public enum WorkItemQueueState
+ {
+ /// <summary>
+ /// The queue is paused
+ /// </summary>
+ Paused,
+
+ /// <summary>
+ /// The queue is running
+ /// </summary>
+ Running,
+
+ /// <summary>
+ /// The queue is stopped
+ /// </summary>
+ Stopped
+ }
+
+ /// <summary>
+ /// A WorkItemQueue holds work items that are ready to
+ /// be run, either initially or after some dependency
+ /// has been satisfied.
+ /// </summary>
+ public class WorkItemQueue
+ {
+ private const int spinCount = 5;
+
+ private Logger log = InternalTrace.GetLogger("WorkItemQueue");
+
+ private readonly ConcurrentQueue<WorkItem> _innerQueue = new ConcurrentQueue<WorkItem>();
+
+ /* This event is used solely for the purpose of having an optimized sleep cycle when
+ * we have to wait on an external event (Add or Remove for instance)
+ */
+ private readonly ManualResetEventSlim _mreAdd = new ManualResetEventSlim(false);
+
+ /* The whole idea is to use these two values in a transactional
+ * way to track and manage the actual data inside the underlying lock-free collection
+ * instead of directly working with it or using external locking.
+ *
+ * They are manipulated with CAS and are guaranteed to increase over time and use
+ * of the instance thus preventing ABA problems.
+ */
+ private int _addId = int.MinValue;
+ private int _removeId = int.MinValue;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WorkItemQueue"/> class.
+ /// </summary>
+ /// <param name="name">The name of the queue.</param>
+ public WorkItemQueue(string name)
+ {
+ Name = name;
+ State = WorkItemQueueState.Paused;
+ MaxCount = 0;
+ ItemsProcessed = 0;
+ }
+
+ #region Properties
+
+ /// <summary>
+ /// Gets the name of the work item queue.
+ /// </summary>
+ public string Name { get; private set; }
+
+ private int _itemsProcessed;
+ /// <summary>
+ /// Gets the total number of items processed so far
+ /// </summary>
+ public int ItemsProcessed
+ {
+ get { return _itemsProcessed; }
+ private set { _itemsProcessed = value; }
+ }
+
+ private int _maxCount;
+
+ /// <summary>
+ /// Gets the maximum number of work items.
+ /// </summary>
+ public int MaxCount
+ {
+ get { return _maxCount; }
+ private set { _maxCount = value; }
+ }
+
+ private int _state;
+ /// <summary>
+ /// Gets the current state of the queue
+ /// </summary>
+ public WorkItemQueueState State
+ {
+ get { return (WorkItemQueueState)_state; }
+ private set { _state = (int)value; }
+ }
+
+ /// <summary>
+ /// Get a bool indicating whether the queue is empty.
+ /// </summary>
+ public bool IsEmpty
+ {
+ get { return _innerQueue.IsEmpty; }
+ }
+
+ #endregion
+
+ #region Public Methods
+
+ /// <summary>
+ /// Enqueue a WorkItem to be processed
+ /// </summary>
+ /// <param name="work">The WorkItem to process</param>
+ public void Enqueue(WorkItem work)
+ {
+ do
+ {
+ int cachedAddId = _addId;
+
+ // Validate that we have are the current enqueuer
+ if (Interlocked.CompareExchange(ref _addId, cachedAddId + 1, cachedAddId) != cachedAddId)
+ continue;
+
+ // Add to the collection
+ _innerQueue.Enqueue(work);
+
+ // Set MaxCount using CAS
+ int i, j = _maxCount;
+ do
+ {
+ i = j;
+ j = Interlocked.CompareExchange(ref _maxCount, Math.Max(i, _innerQueue.Count), i);
+ }
+ while (i != j);
+
+ // Wake up threads that may have been sleeping
+ _mreAdd.Set();
+
+ return;
+ } while (true);
+ }
+
+ /// <summary>
+ /// Dequeue a WorkItem for processing
+ /// </summary>
+ /// <returns>A WorkItem or null if the queue has stopped</returns>
+ public WorkItem Dequeue()
+ {
+ SpinWait sw = new SpinWait();
+
+ do
+ {
+ WorkItemQueueState cachedState = State;
+
+ if (cachedState == WorkItemQueueState.Stopped)
+ return null; // Tell worker to terminate
+
+ int cachedRemoveId = _removeId;
+ int cachedAddId = _addId;
+
+ // Empty case (or paused)
+ if (cachedRemoveId == cachedAddId || cachedState == WorkItemQueueState.Paused)
+ {
+ // Spin a few times to see if something changes
+ if (sw.Count <= spinCount)
+ {
+ sw.SpinOnce();
+ }
+ else
+ {
+ // Reset to wait for an enqueue
+ _mreAdd.Reset();
+
+ // Recheck for an enqueue to avoid a Wait
+ if ((cachedRemoveId != _removeId || cachedAddId != _addId) && cachedState != WorkItemQueueState.Paused)
+ {
+ // Queue is not empty, set the event
+ _mreAdd.Set();
+ continue;
+ }
+
+ // Wait for something to happen
+ _mreAdd.Wait(500);
+ }
+
+ continue;
+ }
+
+ // Validate that we are the current dequeuer
+ if (Interlocked.CompareExchange(ref _removeId, cachedRemoveId + 1, cachedRemoveId) != cachedRemoveId)
+ continue;
+
+
+ // Dequeue our work item
+ WorkItem work;
+ while (!_innerQueue.TryDequeue(out work)) { };
+
+ // Add to items processed using CAS
+ Interlocked.Increment(ref _itemsProcessed);
+
+ return work;
+ } while (true);
+ }
+
+ /// <summary>
+ /// Start or restart processing of items from the queue
+ /// </summary>
+ public void Start()
+ {
+ log.Info("{0} starting", Name);
+
+ if (Interlocked.CompareExchange(ref _state, (int)WorkItemQueueState.Running, (int)WorkItemQueueState.Paused) == (int)WorkItemQueueState.Paused)
+ _mreAdd.Set();
+ }
+
+ /// <summary>
+ /// Signal the queue to stop
+ /// </summary>
+ public void Stop()
+ {
+ log.Info("{0} stopping - {1} WorkItems processed, max size {2}", Name, ItemsProcessed, MaxCount);
+
+ if (Interlocked.Exchange(ref _state, (int)WorkItemQueueState.Stopped) != (int)WorkItemQueueState.Stopped)
+ _mreAdd.Set();
+ }
+
+ /// <summary>
+ /// Pause the queue for restarting later
+ /// </summary>
+ public void Pause()
+ {
+ log.Info("{0} pausing", Name);
+
+ Interlocked.CompareExchange(ref _state, (int)WorkItemQueueState.Paused, (int)WorkItemQueueState.Running);
+ }
+
+ #endregion
+ }
+
+#if NET_2_0 || NET_3_5 || NETCF
+ internal static class ManualResetEventExtensions
+ {
+ public static bool Wait (this ManualResetEvent mre, int millisecondsTimeout)
+ {
+ return mre.WaitOne(millisecondsTimeout, false);
+ }
+ }
+#endif
+
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// The current state of a work item
+ /// </summary>
+ public enum WorkItemState
+ {
+ /// <summary>
+ /// Ready to run or continue
+ /// </summary>
+ Ready,
+
+ /// <summary>
+ /// Work Item is executing
+ /// </summary>
+ Running,
+
+ /// <summary>
+ /// Complete
+ /// </summary>
+ Complete
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012-2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Threading;
+
+namespace NUnit.Framework.Internal.Execution
+{
+ /// <summary>
+ /// The dispatcher needs to do different things at different,
+ /// non-overlapped times. For example, non-parallel tests may
+ /// not be run at the same time as parallel tests. We model
+ /// this using the metaphor of a working shift. The WorkShift
+ /// class associates one or more WorkItemQueues with one or
+ /// more TestWorkers.
+ ///
+ /// Work in the queues is processed until all queues are empty
+ /// and all workers are idle. Both tests are needed because a
+ /// worker that is busy may end up adding more work to one of
+ /// the queues. At that point, the shift is over and another
+ /// shift may begin. This cycle continues until all the tests
+ /// have been run.
+ /// </summary>
+ public class WorkShift
+ {
+ private static Logger log = InternalTrace.GetLogger("WorkShift");
+
+ private object _syncRoot = new object();
+ private int _busyCount = 0;
+
+ // Shift name - used for logging
+ private string _name;
+
+ /// <summary>
+ /// Construct a WorkShift
+ /// </summary>
+ public WorkShift(string name)
+ {
+ _name = name;
+
+ this.IsActive = false;
+ this.Queues = new List<WorkItemQueue>();
+ this.Workers = new List<TestWorker>();
+ }
+
+ #region Public Events and Properties
+
+ /// <summary>
+ /// Event that fires when the shift has ended
+ /// </summary>
+ public event EventHandler EndOfShift;
+
+ /// <summary>
+ /// Gets a flag indicating whether the shift is currently active
+ /// </summary>
+ public bool IsActive { get; private set; }
+
+ /// <summary>
+ /// Gets a list of the queues associated with this shift.
+ /// </summary>
+ /// <remarks>Used for testing</remarks>
+ public IList<WorkItemQueue> Queues { get; private set; }
+
+ /// <summary>
+ /// Gets the list of workers associated with this shift.
+ /// </summary>
+ public IList<TestWorker> Workers { get; private set; }
+
+ /// <summary>
+ /// Gets a bool indicating whether this shift has any work to do
+ /// </summary>
+ public bool HasWork
+ {
+ get
+ {
+ foreach (var q in Queues)
+ if (!q.IsEmpty)
+ return true;
+
+ return false;
+ }
+ }
+
+ #endregion
+
+ #region Public Methods
+
+ /// <summary>
+ /// Add a WorkItemQueue to the shift, starting it if the
+ /// shift is currently active.
+ /// </summary>
+ public void AddQueue(WorkItemQueue queue)
+ {
+ log.Debug("{0} shift adding queue {1}", _name, queue.Name);
+
+ Queues.Add(queue);
+
+ if (this.IsActive)
+ queue.Start();
+ }
+
+ /// <summary>
+ /// Assign a worker to the shift.
+ /// </summary>
+ /// <param name="worker"></param>
+ public void Assign(TestWorker worker)
+ {
+ log.Debug("{0} shift assigned worker {1}", _name, worker.Name);
+
+ Workers.Add(worker);
+
+ worker.Busy += (s, ea) => Interlocked.Increment(ref _busyCount);
+ worker.Idle += (s, ea) =>
+ {
+ // Quick check first using Interlocked.Decrement
+ if (Interlocked.Decrement(ref _busyCount) == 0)
+ lock (_syncRoot)
+ {
+ // Check busy count again under the lock
+ if (_busyCount == 0 && !HasWork)
+ this.EndShift();
+ }
+ };
+
+ worker.Start();
+ }
+
+ /// <summary>
+ /// Start or restart processing for the shift
+ /// </summary>
+ public void Start()
+ {
+ log.Info("{0} shift starting", _name);
+
+ this.IsActive = true;
+
+ foreach (var q in Queues)
+ q.Start();
+ }
+
+ /// <summary>
+ /// End the shift, pausing all queues and raising
+ /// the EndOfShift event.
+ /// </summary>
+ public void EndShift()
+ {
+ log.Info("{0} shift ending", _name);
+
+ this.IsActive = false;
+
+ // Pause all queues
+ foreach (var q in Queues)
+ q.Pause();
+
+ // Signal the dispatcher that shift ended
+ if (EndOfShift != null)
+ EndOfShift(this, EventArgs.Empty);
+ }
+
+ /// <summary>
+ /// Shut down the shift.
+ /// </summary>
+ public void ShutDown()
+ {
+ this.IsActive = false;
+
+ foreach (var q in Queues)
+ q.Stop();
+ }
+
+ /// <summary>
+ /// Cancel (abort or stop) the shift without completing all work
+ /// </summary>
+ /// <param name="force">true if the WorkShift should be aborted, false if it should allow its currently running tests to complete</param>
+ public void Cancel(bool force)
+ {
+ if (force)
+ this.IsActive = false;
+
+ foreach (var w in Workers)
+ w.Cancel(force);
+ }
+
+ #endregion
+ }
+}
+
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Filters
+{
+ /// <summary>
+ /// Combines multiple filters so that a test must pass all
+ /// of them in order to pass this filter.
+ /// </summary>
+ //[Serializable]
+ public class AndFilter : CompositeFilter
+ {
+ /// <summary>
+ /// Constructs an empty AndFilter
+ /// </summary>
+ public AndFilter() { }
+
+ /// <summary>
+ /// Constructs an AndFilter from an array of filters
+ /// </summary>
+ /// <param name="filters"></param>
+ public AndFilter(params ITestFilter[] filters) : base(filters) { }
+
+ /// <summary>
+ /// Checks whether the AndFilter is matched by a test
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ /// <returns>True if all the component filters pass, otherwise false</returns>
+ public override bool Pass( ITest test )
+ {
+ foreach( ITestFilter filter in Filters )
+ if ( !filter.Pass( test ) )
+ return false;
+
+ return true;
+ }
+
+ /// <summary>
+ /// Checks whether the AndFilter is matched by a test
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ /// <returns>True if all the component filters match, otherwise false</returns>
+ public override bool Match( ITest test )
+ {
+ foreach( TestFilter filter in Filters )
+ if ( !filter.Match( test ) )
+ return false;
+
+ return true;
+ }
+
+ /// <summary>
+ /// Checks whether the AndFilter is explicit matched by a test.
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ /// <returns>True if all the component filters explicit match, otherwise false</returns>
+ public override bool IsExplicitMatch( ITest test )
+ {
+ foreach( TestFilter filter in Filters )
+ if ( !filter.IsExplicitMatch( test ) )
+ return false;
+
+ return true;
+ }
+
+ /// <summary>
+ /// Gets the element name
+ /// </summary>
+ /// <value>Element name</value>
+ protected override string ElementName
+ {
+ get { return "and"; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Text;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Filters
+{
+ /// <summary>
+ /// CategoryFilter is able to select or exclude tests
+ /// based on their categories.
+ /// </summary>
+ ///
+ //[Serializable]
+ public class CategoryFilter : ValueMatchFilter
+ {
+ /// <summary>
+ /// Construct a CategoryFilter using a single category name
+ /// </summary>
+ /// <param name="name">A category name</param>
+ public CategoryFilter( string name ) : base(name) { }
+
+ /// <summary>
+ /// Check whether the filter matches a test
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ /// <returns></returns>
+ public override bool Match(ITest test)
+ {
+ IList testCategories = test.Properties[PropertyNames.Category];
+
+ if ( testCategories != null)
+ foreach (string cat in testCategories)
+ if ( Match(cat))
+ return true;
+
+ return false;
+ }
+
+ /// <summary>
+ /// Gets the element name
+ /// </summary>
+ /// <value>Element name</value>
+ protected override string ElementName
+ {
+ get { return "cat"; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Filters
+{
+ /// <summary>
+ /// ClassName filter selects tests based on the class FullName
+ /// </summary>
+ //[Serializable]
+ public class ClassNameFilter : ValueMatchFilter
+ {
+ /// <summary>
+ /// Construct a FullNameFilter for a single name
+ /// </summary>
+ /// <param name="expectedValue">The name the filter will recognize.</param>
+ public ClassNameFilter(string expectedValue) : base(expectedValue) { }
+
+ /// <summary>
+ /// Match a test against a single value.
+ /// </summary>
+ public override bool Match(ITest test)
+ {
+ // tests below the fixture level may have non-null className
+ // but we don't want to match them explicitly.
+ if (!test.IsSuite || test is ParameterizedMethodSuite || test.ClassName == null)
+ return false;
+
+ return Match(test.ClassName);
+ }
+
+ /// <summary>
+ /// Gets the element name
+ /// </summary>
+ /// <value>Element name</value>
+ protected override string ElementName
+ {
+ get { return "class"; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Filters
+{
+ /// <summary>
+ /// A base class for multi-part filters
+ /// </summary>
+ public abstract class CompositeFilter : TestFilter
+ {
+ /// <summary>
+ /// Constructs an empty CompositeFilter
+ /// </summary>
+ public CompositeFilter()
+ {
+ Filters = new List<ITestFilter>();
+ }
+
+ /// <summary>
+ /// Constructs a CompositeFilter from an array of filters
+ /// </summary>
+ /// <param name="filters"></param>
+ public CompositeFilter( params ITestFilter[] filters )
+ {
+ Filters = new List<ITestFilter>(filters);
+ }
+
+ /// <summary>
+ /// Adds a filter to the list of filters
+ /// </summary>
+ /// <param name="filter">The filter to be added</param>
+ public void Add(ITestFilter filter)
+ {
+ Filters.Add(filter);
+ }
+
+ /// <summary>
+ /// Return a list of the composing filters.
+ /// </summary>
+ public IList<ITestFilter> Filters { get; private set; }
+
+ /// <summary>
+ /// Checks whether the CompositeFilter is matched by a test.
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ public abstract override bool Pass(ITest test);
+
+ /// <summary>
+ /// Checks whether the CompositeFilter is matched by a test.
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ public abstract override bool Match(ITest test);
+
+ /// <summary>
+ /// Checks whether the CompositeFilter is explicit matched by a test.
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ public abstract override bool IsExplicitMatch(ITest test);
+
+ /// <summary>
+ /// Adds an XML node
+ /// </summary>
+ /// <param name="parentNode">Parent node</param>
+ /// <param name="recursive">True if recursive</param>
+ /// <returns>The added XML node</returns>
+ public override TNode AddToXml(TNode parentNode, bool recursive)
+ {
+ TNode result = parentNode.AddElement(ElementName);
+
+ if (recursive)
+ foreach (ITestFilter filter in Filters)
+ filter.AddToXml(result, true);
+
+ return result;
+ }
+
+ /// <summary>
+ /// Gets the element name
+ /// </summary>
+ /// <value>Element name</value>
+ protected abstract string ElementName { get; }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Filters
+{
+ /// <summary>
+ /// FullName filter selects tests based on their FullName
+ /// </summary>
+ //[Serializable]
+ public class FullNameFilter : ValueMatchFilter
+ {
+ /// <summary>
+ /// Construct a FullNameFilter for a single name
+ /// </summary>
+ /// <param name="expectedValue">The name the filter will recognize.</param>
+ public FullNameFilter(string expectedValue) : base(expectedValue) { }
+
+ /// <summary>
+ /// Match a test against a single value.
+ /// </summary>
+ public override bool Match(ITest test)
+ {
+ return Match(test.FullName);
+ }
+
+ /// <summary>
+ /// Gets the element name
+ /// </summary>
+ /// <value>Element name</value>
+ protected override string ElementName
+ {
+ get { return "test"; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2013 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Filters
+{
+ /// <summary>
+ /// IdFilter selects tests based on their id
+ /// </summary>
+ //[Serializable]
+ public class IdFilter : ValueMatchFilter
+ {
+ /// <summary>
+ /// Construct an IdFilter for a single value
+ /// </summary>
+ /// <param name="id">The id the filter will recognize.</param>
+ public IdFilter(string id) : base (id) { }
+
+ /// <summary>
+ /// Match a test against a single value.
+ /// </summary>
+ public override bool Match(ITest test)
+ {
+ // We make a direct test here rather than calling ValueMatchFilter.Match
+ // because regular expressions are not supported for ID.
+ return test.Id == ExpectedValue;
+ }
+
+ /// <summary>
+ /// Gets the element name
+ /// </summary>
+ /// <value>Element name</value>
+ protected override string ElementName
+ {
+ get { return "id"; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Filters
+{
+ /// <summary>
+ /// FullName filter selects tests based on their FullName
+ /// </summary>
+ //[Serializable]
+ public class MethodNameFilter : ValueMatchFilter
+ {
+ /// <summary>
+ /// Construct a MethodNameFilter for a single name
+ /// </summary>
+ /// <param name="expectedValue">The name the filter will recognize.</param>
+ public MethodNameFilter(string expectedValue) : base(expectedValue) { }
+
+ /// <summary>
+ /// Match a test against a single value.
+ /// </summary>
+ public override bool Match(ITest test)
+ {
+ return Match(test.MethodName);
+ }
+
+ /// <summary>
+ /// Gets the element name
+ /// </summary>
+ /// <value>Element name</value>
+ protected override string ElementName
+ {
+ get { return "method"; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Filters
+{
+ /// <summary>
+ /// NotFilter negates the operation of another filter
+ /// </summary>
+ //[Serializable]
+ public class NotFilter : TestFilter
+ {
+ /// <summary>
+ /// Construct a not filter on another filter
+ /// </summary>
+ /// <param name="baseFilter">The filter to be negated</param>
+ public NotFilter( TestFilter baseFilter)
+ {
+ BaseFilter = baseFilter;
+ }
+
+ /// <summary>
+ /// Gets the base filter
+ /// </summary>
+ public TestFilter BaseFilter { get; private set; }
+
+ /// <summary>
+ /// Determine if a particular test passes the filter criteria. The default
+ /// implementation checks the test itself, its parents and any descendants.
+ ///
+ /// Derived classes may override this method or any of the Match methods
+ /// to change the behavior of the filter.
+ /// </summary>
+ /// <param name="test">The test to which the filter is applied</param>
+ /// <returns>True if the test passes the filter, otherwise false</returns>
+ public override bool Pass(ITest test)
+ {
+ return !BaseFilter.Match (test) && !BaseFilter.MatchParent (test);
+ }
+
+ /// <summary>
+ /// Check whether the filter matches a test
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ /// <returns>True if it matches, otherwise false</returns>
+ public override bool Match( ITest test )
+ {
+ return !BaseFilter.Match( test );
+ }
+
+ /// <summary>
+ /// Determine if a test matches the filter expicitly. That is, it must
+ /// be a direct match of the test itself or one of it's children.
+ /// </summary>
+ /// <param name="test">The test to which the filter is applied</param>
+ /// <returns>True if the test matches the filter explicityly, otherwise false</returns>
+ public override bool IsExplicitMatch(ITest test)
+ {
+ return false;
+ }
+
+ ///// <summary>
+ ///// Determine whether any descendant of the test matches the filter criteria.
+ ///// </summary>
+ ///// <param name="test">The test to be matched</param>
+ ///// <returns>True if at least one descendant matches the filter criteria</returns>
+ //protected override bool MatchDescendant(ITest test)
+ //{
+ // if (!test.HasChildren || test.Tests == null || TopLevel && test.RunState == RunState.Explicit)
+ // return false;
+
+ // foreach (ITest child in test.Tests)
+ // {
+ // if (Match(child) || MatchDescendant(child))
+ // return true;
+ // }
+
+ // return false;
+ //}
+
+ /// <summary>
+ /// Adds an XML node
+ /// </summary>
+ /// <param name="parentNode">Parent node</param>
+ /// <param name="recursive">True if recursive</param>
+ /// <returns>The added XML node</returns>
+ public override TNode AddToXml(TNode parentNode, bool recursive)
+ {
+ TNode result = parentNode.AddElement("not");
+ if (recursive)
+ BaseFilter.AddToXml(result, true);
+ return result;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Filters
+{
+ /// <summary>
+ /// Combines multiple filters so that a test must pass one
+ /// of them in order to pass this filter.
+ /// </summary>
+ //[Serializable]
+ public class OrFilter : CompositeFilter
+ {
+ /// <summary>
+ /// Constructs an empty OrFilter
+ /// </summary>
+ public OrFilter() { }
+
+ /// <summary>
+ /// Constructs an AndFilter from an array of filters
+ /// </summary>
+ /// <param name="filters"></param>
+ public OrFilter( params ITestFilter[] filters ) : base(filters) { }
+
+ /// <summary>
+ /// Checks whether the OrFilter is matched by a test
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ /// <returns>True if any of the component filters pass, otherwise false</returns>
+ public override bool Pass( ITest test )
+ {
+ foreach( ITestFilter filter in Filters )
+ if ( filter.Pass( test ) )
+ return true;
+
+ return false;
+ }
+
+ /// <summary>
+ /// Checks whether the OrFilter is matched by a test
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ /// <returns>True if any of the component filters match, otherwise false</returns>
+ public override bool Match( ITest test )
+ {
+ foreach( TestFilter filter in Filters )
+ if ( filter.Match( test ) )
+ return true;
+
+ return false;
+ }
+
+ /// <summary>
+ /// Checks whether the OrFilter is explicit matched by a test
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ /// <returns>True if any of the component filters explicit match, otherwise false</returns>
+ public override bool IsExplicitMatch( ITest test )
+ {
+ foreach( TestFilter filter in Filters )
+ if ( filter.IsExplicitMatch( test ) )
+ return true;
+
+ return false;
+ }
+
+ /// <summary>
+ /// Gets the element name
+ /// </summary>
+ /// <value>Element name</value>
+ protected override string ElementName
+ {
+ get { return "or"; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Text;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Filters
+{
+ /// <summary>
+ /// PropertyFilter is able to select or exclude tests
+ /// based on their properties.
+ /// </summary>
+ ///
+ //[Serializable]
+ public class PropertyFilter : ValueMatchFilter
+ {
+ private string _propertyName;
+
+ /// <summary>
+ /// Construct a PropertyFilter using a property name and expected value
+ /// </summary>
+ /// <param name="propertyName">A property name</param>
+ /// <param name="expectedValue">The expected value of the property</param>
+ public PropertyFilter(string propertyName, string expectedValue) : base(expectedValue)
+ {
+ _propertyName = propertyName;
+ }
+
+ /// <summary>
+ /// Check whether the filter matches a test
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ /// <returns></returns>
+ public override bool Match(ITest test)
+ {
+ IList values = test.Properties[_propertyName];
+
+ if (values != null)
+ foreach (string val in values)
+ if (Match(val))
+ return true;
+
+ return false;
+ }
+
+ /// <summary>
+ /// Adds an XML node
+ /// </summary>
+ /// <param name="parentNode">Parent node</param>
+ /// <param name="recursive">True if recursive</param>
+ /// <returns>The added XML node</returns>
+ public override TNode AddToXml(TNode parentNode, bool recursive)
+ {
+ TNode result = base.AddToXml(parentNode, recursive);
+ result.AddAttribute("name", _propertyName);
+ return result;
+ }
+
+ /// <summary>
+ /// Gets the element name
+ /// </summary>
+ /// <value>Element name</value>
+ protected override string ElementName
+ {
+ get { return "prop"; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Filters
+{
+ /// <summary>
+ /// TestName filter selects tests based on their Name
+ /// </summary>
+ //[Serializable]
+ public class TestNameFilter : ValueMatchFilter
+ {
+ /// <summary>
+ /// Construct a TestNameFilter for a single name
+ /// </summary>
+ /// <param name="expectedValue">The name the filter will recognize.</param>
+ public TestNameFilter(string expectedValue) : base(expectedValue) { }
+
+ /// <summary>
+ /// Match a test against a single value.
+ /// </summary>
+ public override bool Match(ITest test)
+ {
+ return Match(test.Name);
+ }
+
+ /// <summary>
+ /// Gets the element name
+ /// </summary>
+ /// <value>Element name</value>
+ protected override string ElementName
+ {
+ get { return "name"; }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2013 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Text.RegularExpressions;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal.Filters
+{
+ /// <summary>
+ /// ValueMatchFilter selects tests based on some value, which
+ /// is expected to be contained in the test.
+ /// </summary>
+ //[Serializable]
+ public abstract class ValueMatchFilter : TestFilter
+ {
+ /// <summary>
+ /// Returns the value matched by the filter - used for testing
+ /// </summary>
+ public string ExpectedValue { get; private set; }
+
+ /// <summary>
+ /// Indicates whether the value is a regular expression
+ /// </summary>
+ public bool IsRegex { get; set; }
+
+ /// <summary>
+ /// Construct a ValueMatchFilter for a single value.
+ /// </summary>
+ /// <param name="expectedValue">The value to be included.</param>
+ public ValueMatchFilter(string expectedValue)
+ {
+ ExpectedValue = expectedValue;
+ }
+
+ /// <summary>
+ /// Match the input provided by the derived class
+ /// </summary>
+ /// <param name="input">The value to be matchedT</param>
+ /// <returns>True for a match, false otherwise.</returns>
+ protected bool Match(string input)
+ {
+ if (IsRegex)
+ return input != null && new Regex(ExpectedValue).IsMatch(input);
+ else
+ return ExpectedValue == input;
+ }
+
+ /// <summary>
+ /// Adds an XML node
+ /// </summary>
+ /// <param name="parentNode">Parent node</param>
+ /// <param name="recursive">True if recursive</param>
+ /// <returns>The added XML node</returns>
+ public override TNode AddToXml(TNode parentNode, bool recursive)
+ {
+ TNode result = parentNode.AddElement(ElementName, ExpectedValue);
+ if (IsRegex)
+ result.AddAttribute("re", "1");
+ return result;
+ }
+
+ /// <summary>
+ /// Gets the element name
+ /// </summary>
+ /// <value>Element name</value>
+ protected abstract string ElementName { get; }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// GenericMethodHelper is able to deduce the Type arguments for
+ /// a generic method from the actual arguments provided.
+ /// </summary>
+ public class GenericMethodHelper
+ {
+ /// <summary>
+ /// Construct a GenericMethodHelper for a method
+ /// </summary>
+ /// <param name="method">MethodInfo for the method to examine</param>
+ public GenericMethodHelper(MethodInfo method)
+ {
+ Guard.ArgumentValid(method.IsGenericMethod, "Specified method must be generic", "method");
+
+ Method = method;
+
+ TypeParms = Method.GetGenericArguments();
+ TypeArgs = new Type[TypeParms.Length];
+
+ var parms = Method.GetParameters();
+ ParmTypes = new Type[parms.Length];
+ for (int i = 0; i < parms.Length; i++)
+ ParmTypes[i] = parms[i].ParameterType;
+ }
+
+ private MethodInfo Method { get; set; }
+
+ private Type[] TypeParms { get; set; }
+ private Type[] TypeArgs { get; set; }
+
+ private Type[] ParmTypes { get; set; }
+
+ /// <summary>
+ /// Return the type argments for the method, deducing them
+ /// from the arguments actually provided.
+ /// </summary>
+ /// <param name="argList">The arguments to the method</param>
+ /// <returns>An array of type arguments.</returns>
+ public Type[] GetTypeArguments(object[] argList)
+ {
+ Guard.ArgumentValid(argList.Length == ParmTypes.Length, "Supplied arguments do not match required method parameters", "argList");
+
+ for (int argIndex = 0; argIndex < ParmTypes.Length; argIndex++)
+ {
+ var arg = argList[argIndex];
+
+ if (arg != null)
+ {
+ Type argType = arg.GetType();
+ TryApplyArgType(ParmTypes[argIndex], argType);
+ }
+ }
+
+ return TypeArgs;
+ }
+
+ private void TryApplyArgType(Type parmType, Type argType)
+ {
+ if (parmType.IsGenericParameter)
+ {
+ ApplyArgType(parmType, argType);
+ }
+ else if (parmType.GetTypeInfo().ContainsGenericParameters)
+ {
+ var genericArgTypes = parmType.GetGenericArguments();
+
+ if (argType.HasElementType)
+ {
+ ApplyArgType(genericArgTypes[0], argType.GetElementType());
+ }
+ else if (argType.GetTypeInfo().IsGenericType && IsAssignableToGenericType(argType, parmType))
+ {
+ Type[] argTypes = argType.GetGenericArguments();
+
+ if (argTypes.Length == genericArgTypes.Length)
+ for (int i = 0; i < genericArgTypes.Length; i++)
+ TryApplyArgType(genericArgTypes[i], argTypes[i]);
+ }
+ }
+ }
+
+ private void ApplyArgType(Type parmType, Type argType)
+ {
+ // Note: parmType must be generic parameter type - checked by caller
+#if NETCF
+ var index = Array.IndexOf(TypeParms, parmType);
+#else
+ var index = parmType.GenericParameterPosition;
+#endif
+ TypeArgs[index] = TypeHelper.BestCommonType(TypeArgs[index], argType);
+ }
+
+ // Simulates IsAssignableTo generics
+ private bool IsAssignableToGenericType(Type givenType, Type genericType)
+ {
+ var interfaceTypes = givenType.GetInterfaces();
+
+ foreach (var iterator in interfaceTypes)
+ {
+ if (iterator.GetTypeInfo().IsGenericType)
+ {
+ // The Type returned by GetGenericTyeDefinition may have the
+ // FullName set to null, so we do our own comparison
+ Type gtd = iterator.GetGenericTypeDefinition();
+ if (gtd.Name == genericType.Name && gtd.Namespace == genericType.Namespace)
+ return true;
+ }
+ }
+
+ if (givenType.GetTypeInfo().IsGenericType)
+ {
+ // The Type returned by GetGenericTyeDefinition may have the
+ // FullName set to null, so we do our own comparison
+ Type gtd = givenType.GetGenericTypeDefinition();
+ if (gtd.Name == genericType.Name && gtd.Namespace == genericType.Namespace)
+ return true;
+ }
+
+ Type baseType = givenType.GetTypeInfo().BaseType;
+ if (baseType == null)
+ return false;
+
+ return IsAssignableToGenericType(baseType, genericType);
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Internal
+{
+ using System;
+#if !NETCF
+ //using System.Runtime.Serialization;
+#endif
+
+ /// <summary>
+ /// InvalidTestFixtureException is thrown when an appropriate test
+ /// fixture constructor using the provided arguments cannot be found.
+ /// </summary>
+#if !NETCF
+ //[Serializable]
+#endif
+ public class InvalidDataSourceException : Exception
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="InvalidTestFixtureException"/> class.
+ /// </summary>
+ public InvalidDataSourceException() : base() {}
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="InvalidTestFixtureException"/> class.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ public InvalidDataSourceException(string message) : base(message)
+ {}
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="InvalidTestFixtureException"/> class.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="inner">The inner.</param>
+ public InvalidDataSourceException(string message, Exception inner) : base(message, inner)
+ { }
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Serialization Constructor
+ /// </summary>
+ protected InvalidDataSourceException(SerializationInfo info,
+ StreamingContext context) : base(info,context){}
+#endif
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2006 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Internal
+{
+ using System;
+#if !NETCF
+ //using System.Runtime.Serialization;
+#endif
+
+ /// <summary>
+ /// InvalidTestFixtureException is thrown when an appropriate test
+ /// fixture constructor using the provided arguments cannot be found.
+ /// </summary>
+#if !NETCF
+ //[Serializable]
+#endif
+ public class InvalidTestFixtureException : Exception
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="InvalidTestFixtureException"/> class.
+ /// </summary>
+ public InvalidTestFixtureException() : base() {}
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="InvalidTestFixtureException"/> class.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ public InvalidTestFixtureException(string message) : base(message)
+ {}
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="InvalidTestFixtureException"/> class.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="inner">The inner.</param>
+ public InvalidTestFixtureException(string message, Exception inner) : base(message, inner)
+ { }
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Serialization Constructor
+ /// </summary>
+ protected InvalidTestFixtureException(SerializationInfo info,
+ StreamingContext context) : base(info,context){}
+#endif
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+using System.Collections.Generic;
+using System.IO;
+using NUnit.Framework.TUnit;
+
+#if PORTABLE
+using System.Linq;
+#endif
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// The MethodWrapper class wraps a MethodInfo so that it may
+ /// be used in a platform-independent manner.
+ /// </summary>
+ public class MethodWrapper : IMethodInfo
+ {
+ /// <summary>
+ /// Construct a MethodWrapper for a Type and a MethodInfo.
+ /// </summary>
+ public MethodWrapper(Type type, MethodInfo method)
+ {
+ TypeInfo = new TypeWrapper(type);
+ MethodInfo = method;
+ }
+
+ /// <summary>
+ /// Construct a MethodInfo for a given Type and method name.
+ /// </summary>
+ public MethodWrapper(Type type, string methodName)
+ {
+ TypeInfo = new TypeWrapper(type);
+ MethodInfo = type.GetMethod(methodName);
+ }
+
+ #region IMethod Implementation
+
+ /// <summary>
+ /// Gets the Type from which this method was reflected.
+ /// </summary>
+ public ITypeInfo TypeInfo { get; private set; }
+
+ /// <summary>
+ /// Gets the MethodInfo for this method.
+ /// </summary>
+ public MethodInfo MethodInfo { get; private set; }
+
+ /// <summary>
+ /// Gets the name of the method.
+ /// </summary>
+ public string Name
+ {
+ get { return MethodInfo.Name; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the method is abstract.
+ /// </summary>
+ public bool IsAbstract
+ {
+ get { return MethodInfo.IsAbstract; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the method is public.
+ /// </summary>
+ public bool IsPublic
+ {
+ get { return MethodInfo.IsPublic; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the method contains unassigned generic type parameters.
+ /// </summary>
+ public bool ContainsGenericParameters
+ {
+ get { return MethodInfo.ContainsGenericParameters; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the method is a generic method.
+ /// </summary>
+ public bool IsGenericMethod
+ {
+ get { return MethodInfo.IsGenericMethod; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the MethodInfo represents the definition of a generic method.
+ /// </summary>
+ public bool IsGenericMethodDefinition
+ {
+ get { return MethodInfo.IsGenericMethodDefinition; }
+ }
+
+ /// <summary>
+ /// Gets the return Type of the method.
+ /// </summary>
+ public ITypeInfo ReturnType
+ {
+ get { return new TypeWrapper(MethodInfo.ReturnType); }
+ }
+
+ /// <summary>
+ /// Gets the parameters of the method.
+ /// </summary>
+ /// <returns></returns>
+ public IParameterInfo[] GetParameters()
+ {
+ var parameters = MethodInfo.GetParameters();
+ var result = new IParameterInfo[parameters.Length];
+
+ for (int i = 0; i < parameters.Length; i++)
+ result[i] = new ParameterWrapper(this, parameters[i]);
+
+ return result;
+ }
+
+ /// <summary>
+ /// Returns the Type arguments of a generic method or the Type parameters of a generic method definition.
+ /// </summary>
+ public Type[] GetGenericArguments()
+ {
+ return MethodInfo.GetGenericArguments();
+ }
+
+ /// <summary>
+ /// Replaces the type parameters of the method with the array of types provided and returns a new IMethodInfo.
+ /// </summary>
+ /// <param name="typeArguments">The type arguments to be used</param>
+ /// <returns>A new IMethodInfo with the type arguments replaced</returns>
+ public IMethodInfo MakeGenericMethod(params Type[] typeArguments)
+ {
+ return new MethodWrapper(TypeInfo.Type, MethodInfo.MakeGenericMethod(typeArguments));
+ }
+
+ /// <summary>
+ /// Returns an array of custom attributes of the specified type applied to this method
+ /// </summary>
+ public T[] GetCustomAttributes<T>(bool inherit) where T : class
+ {
+#if PORTABLE
+ //return MethodInfo.GetAttributes<T>(inherit).ToArray();
+ var allAttributes = MethodInfo.GetCustomAttributes();
+ List<string> attributeDic = new List<string>();
+ foreach (Attribute atb in allAttributes)
+ {
+ attributeDic.Add(atb.GetType().FullName);
+ }
+ var assembly = MethodInfo.DeclaringType.GetTypeInfo().Assembly;
+ List<T> objects = new List<T>();
+
+ string path = System.IO.Path.GetDirectoryName(assembly.Location);
+
+ if (!Directory.Exists(path))
+ {
+ TLogger.WriteError(TLogger.ExceptionTag, "" + path + " - not a directory");
+ return objects.ToArray();
+ }
+ foreach (var assemblyPath in Directory.GetFiles(path, "*.Tests.dll"))
+ {
+
+ IEnumerable<Type> types;
+ try
+ {
+ Assembly please = AssemblyHelper.Load(assemblyPath);
+ if (please == null) continue;
+ types = please.GetTypes().Where(p => !p.GetTypeInfo().IsAbstract && p.GetTypeInfo().IsClass && p.GetTypeInfo().ImplementedInterfaces.Contains(typeof(T)));
+ }
+ catch (Exception)
+ {
+ continue;
+ }
+ for (int i = 0; i < types.Count(); i++)
+ {
+ try
+ {
+ if (attributeDic.Contains(types.ElementAt(i).FullName))
+ {
+ objects.Add((T)Activator.CreateInstance(types.ElementAt(i)));
+ }
+ }
+ catch (Exception)
+ {
+ //TLogger.Write(TLogger.ExceptionTag, ex.ToString());
+ }
+ }
+ }
+
+ return objects.ToArray();
+#else
+ return (T[])MethodInfo.GetCustomAttributes(typeof(T), inherit);
+#endif
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether one or more attributes of the spcified type are defined on the method.
+ /// </summary>
+ public bool IsDefined<T>(bool inherit)
+ {
+#if PORTABLE
+ return MethodInfo.GetCustomAttributes(inherit).Any(a => typeof(T).IsAssignableFrom(a.GetType()));
+#else
+ return MethodInfo.IsDefined(typeof(T), inherit);
+#endif
+ }
+
+ /// <summary>
+ /// Invokes the method, converting any TargetInvocationException to an NUnitException.
+ /// </summary>
+ /// <param name="fixture">The object on which to invoke the method</param>
+ /// <param name="args">The argument list for the method</param>
+ /// <returns>The return value from the invoked method</returns>
+ public object Invoke(object fixture, params object[] args)
+ {
+ return Reflect.InvokeMethod(MethodInfo, fixture, args);
+ }
+
+ /// <summary>
+ /// Override ToString() so that error messages in NUnit's own tests make sense
+ /// </summary>
+ public override string ToString()
+ {
+ return MethodInfo.Name;
+ }
+
+ #endregion
+
+ #region extra
+ private string GetAssemblyName(string assemblyFullPath)
+ {
+
+ string[] delimiter1 = { "\\" };
+ string[] delimiter2 = { "/" };
+ string[] delimiterDot = { "." };
+ string[] strAry;
+ string returnValue = "";
+ try
+ {
+ strAry = assemblyFullPath.Split(delimiter1, StringSplitOptions.None);
+
+ if (strAry.Length < 2)
+ strAry = assemblyFullPath.Split(delimiter2, StringSplitOptions.None);
+
+ foreach (string str in strAry)
+ {
+ if (str.Contains(".Tests.dll"))
+ {
+ string[] strSplit = str.Split(delimiterDot, StringSplitOptions.None);
+ returnValue = strSplit[0];
+ //LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, "check : "+ returnValue);
+ break;
+ }
+ }
+ }
+ catch (Exception)
+ {
+ }
+
+ return returnValue;
+ }
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Internal
+{
+ using System;
+#if !NETCF
+ //using System.Runtime.Serialization;
+#endif
+
+ /// <summary>
+ /// Thrown when an assertion failed. Here to preserve the inner
+ /// exception and hence its stack trace.
+ /// </summary>
+#if !NETCF
+ //[Serializable]
+#endif
+ public class NUnitException : Exception
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NUnitException"/> class.
+ /// </summary>
+ public NUnitException () : base()
+ {}
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NUnitException"/> class.
+ /// </summary>
+ /// <param name="message">The error message that explains
+ /// the reason for the exception</param>
+ public NUnitException(string message) : base (message)
+ {}
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NUnitException"/> class.
+ /// </summary>
+ /// <param name="message">The error message that explains
+ /// the reason for the exception</param>
+ /// <param name="inner">The exception that caused the
+ /// current exception</param>
+ public NUnitException(string message, Exception inner) :
+ base(message, inner)
+ { }
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Serialization Constructor
+ /// </summary>
+ protected NUnitException(SerializationInfo info,
+ StreamingContext context) : base(info,context){}
+#endif
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if NETCF
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Reflection;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ static class NetCFExtensions
+ {
+ public static IMethodInfo MakeGenericMethodEx(this IMethodInfo method, object[] arguments)
+ {
+ var newMi = method.MethodInfo.MakeGenericMethodEx(arguments);
+ if (newMi == null) return null;
+
+ return new MethodWrapper(method.TypeInfo.Type, newMi);
+ }
+
+ public static MethodInfo MakeGenericMethodEx(this MethodInfo mi, object[] arguments)
+ {
+ return mi.MakeGenericMethodEx(arguments.Select(a => a == null ? typeof(object) : (a is Type ? typeof(Type) : a.GetType())).ToArray());
+ }
+
+ public static MethodInfo MakeGenericMethodEx(this MethodInfo mi, Type[] types)
+ {
+ if(!mi.ContainsGenericParameters)
+ return mi;
+
+ if(!mi.IsGenericMethodDefinition)
+ return mi.MakeGenericMethod(types);
+
+ var args = mi.GetGenericArguments();
+
+ if(args.Length == types.Length)
+ return mi.MakeGenericMethod(types);
+
+ if(args.Length > types.Length)
+ return null;
+
+ var tai = new TypeArrayIterator(types, args.Length);
+
+ foreach(var ta in tai)
+ {
+ var newMi = mi.MakeGenericMethod(ta);
+ var pa = newMi.GetParameters();
+ if(types.SequenceEqual(pa.Select(p => p.ParameterType)))
+ return newMi;
+ }
+
+ foreach(var ta in tai)
+ {
+ var newMi = mi.MakeGenericMethod(ta);
+ var pa = newMi.GetParameters();
+ if(types.Select((t,ix) => (Type)TypeHelper.BestCommonType(t, pa[ix].ParameterType)).SequenceEqual(pa.Select(p => p.ParameterType)))
+ return newMi;
+ }
+
+ return null;
+ }
+
+ }
+
+ internal class TypeArrayIterator : IEnumerable<Type[]>
+ {
+ private Type[] _types;
+ private int _neededLength;
+
+ public TypeArrayIterator(Type[] types, int neededLength)
+ {
+ _types = types;
+ _neededLength = neededLength;
+ }
+
+#region IEnumerable<CType[]> Members
+
+ public IEnumerator<Type[]> GetEnumerator()
+ {
+ var indices = new int[_neededLength];
+ while(true)
+ {
+ var results = new List<Type> ();
+
+ for(int i = 0; i < _neededLength; ++i)
+ results.Add(_types[indices[i]]);
+
+ if(indices.Distinct().Count() == _neededLength)
+ yield return results.ToArray();
+
+ for(int j = _neededLength - 1; j >= 0; --j)
+ {
+ if(++indices[j] < _types.Length)
+ break;
+
+ if(j == 0)
+ yield break;
+
+ indices[j] = 0;
+ }
+ }
+ }
+
+#endregion
+
+#region IEnumerable Members
+
+ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+
+#endregion
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2016 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !PORTABLE
+using Microsoft.Win32;
+using System;
+using System.Runtime.InteropServices;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// OSPlatform represents a particular operating system platform
+ /// </summary>
+ public class OSPlatform
+ {
+ readonly PlatformID _platform;
+ readonly Version _version;
+ readonly ProductType _product;
+
+#region Static Members
+ private static readonly Lazy<OSPlatform> currentPlatform = new Lazy<OSPlatform> (() =>
+ {
+ OSPlatform currentPlatform;
+
+ OperatingSystem os = Environment.OSVersion;
+
+#if SILVERLIGHT || NETCF
+ // TODO: Runtime silverlight detection?
+ currentPlatform = new OSPlatform(os.Platform, os.Version);
+#else
+ if (os.Platform == PlatformID.Win32NT && os.Version.Major >= 5)
+ {
+ OSVERSIONINFOEX osvi = new OSVERSIONINFOEX();
+ osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
+ GetVersionEx(ref osvi);
+ if (os.Version.Major == 6 && os.Version.Minor >= 2)
+ os = new OperatingSystem(os.Platform, GetWindows81PlusVersion(os.Version));
+ currentPlatform = new OSPlatform(os.Platform, os.Version, (ProductType)osvi.ProductType);
+ }
+ else if (CheckIfIsMacOSX(os.Platform))
+ {
+ // Mono returns PlatformID.Unix for OSX (see http://www.mono-project.com/docs/faq/technical/#how-to-detect-the-execution-platform)
+ // The above check uses uname to confirm it is MacOSX and we change the PlatformId here.
+ currentPlatform = new OSPlatform(PlatformID.MacOSX, os.Version);
+ }
+ else
+ currentPlatform = new OSPlatform(os.Platform, os.Version);
+#endif
+ return currentPlatform;
+ });
+
+
+ /// <summary>
+ /// Platform ID for Unix as defined by Microsoft .NET 2.0 and greater
+ /// </summary>
+ public static readonly PlatformID UnixPlatformID_Microsoft = (PlatformID)4;
+
+ /// <summary>
+ /// Platform ID for Unix as defined by Mono
+ /// </summary>
+ public static readonly PlatformID UnixPlatformID_Mono = (PlatformID)128;
+
+ /// <summary>
+ /// Platform ID for XBox as defined by .NET and Mono, but not CF
+ /// </summary>
+ public static readonly PlatformID XBoxPlatformID = (PlatformID)5;
+
+ /// <summary>
+ /// Platform ID for MacOSX as defined by .NET and Mono, but not CF
+ /// </summary>
+ public static readonly PlatformID MacOSXPlatformID = (PlatformID)6;
+
+ /// <summary>
+ /// Get the OSPlatform under which we are currently running
+ /// </summary>
+ public static OSPlatform CurrentPlatform
+ {
+ get
+ {
+ return currentPlatform.Value;
+ }
+ }
+
+#if !SILVERLIGHT && !NETCF
+ /// <summary>
+ /// Gets the actual OS Version, not the incorrect value that might be
+ /// returned for Win 8.1 and Win 10
+ /// </summary>
+ /// <remarks>
+ /// If an application is not manifested as Windows 8.1 or Windows 10,
+ /// the version returned from Environment.OSVersion will not be 6.3 and 10.0
+ /// respectively, but will be 6.2 and 6.3. The correct value can be found in
+ /// the registry.
+ /// </remarks>
+ /// <param name="version">The original version</param>
+ /// <returns>The correct OS version</returns>
+ private static Version GetWindows81PlusVersion(Version version)
+ {
+ try
+ {
+ using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
+ {
+ if (key != null)
+ {
+ var buildStr = key.GetValue("CurrentBuildNumber") as string;
+ int build = 0;
+ int.TryParse(buildStr, out build);
+
+ // These two keys are in Windows 10 only and are DWORDS
+ var major = key.GetValue("CurrentMajorVersionNumber") as int?;
+ var minor = key.GetValue("CurrentMinorVersionNumber") as int?;
+ if (major.HasValue && minor.HasValue)
+ {
+ return new Version(major.Value, minor.Value, build);
+ }
+
+ // If we get here, we are not Windows 10, so we are Windows 8
+ // or 8.1. 8.1 might report itself as 6.2, but will have 6.3
+ // in the registry. We can't do this earlier because for backwards
+ // compatibility, Windows 10 also has 6.3 for this key.
+ var currentVersion = key.GetValue("CurrentVersion") as string;
+ if(currentVersion == "6.3")
+ {
+ return new Version(6, 3, build);
+ }
+ }
+ }
+ }
+ catch (Exception)
+ {
+ }
+ return version;
+ }
+#endif
+#endregion
+
+#region Members used for Win32NT platform only
+ /// <summary>
+ /// Product Type Enumeration used for Windows
+ /// </summary>
+ public enum ProductType
+ {
+ /// <summary>
+ /// Product type is unknown or unspecified
+ /// </summary>
+ Unknown,
+
+ /// <summary>
+ /// Product type is Workstation
+ /// </summary>
+ WorkStation,
+
+ /// <summary>
+ /// Product type is Domain Controller
+ /// </summary>
+ DomainController,
+
+ /// <summary>
+ /// Product type is Server
+ /// </summary>
+ Server,
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ struct OSVERSIONINFOEX
+ {
+ public uint dwOSVersionInfoSize;
+ public readonly uint dwMajorVersion;
+ public readonly uint dwMinorVersion;
+ public readonly uint dwBuildNumber;
+ public readonly uint dwPlatformId;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
+ public readonly string szCSDVersion;
+ public readonly Int16 wServicePackMajor;
+ public readonly Int16 wServicePackMinor;
+ public readonly Int16 wSuiteMask;
+ public readonly Byte ProductType;
+ public readonly Byte Reserved;
+ }
+
+ [DllImport("Kernel32.dll")]
+ private static extern bool GetVersionEx(ref OSVERSIONINFOEX osvi);
+#endregion
+
+ /// <summary>
+ /// Construct from a platform ID and version
+ /// </summary>
+ public OSPlatform(PlatformID platform, Version version)
+ {
+ _platform = platform;
+ _version = version;
+ }
+
+ /// <summary>
+ /// Construct from a platform ID, version and product type
+ /// </summary>
+ public OSPlatform(PlatformID platform, Version version, ProductType product)
+ : this( platform, version )
+ {
+ _product = product;
+ }
+
+ /// <summary>
+ /// Get the platform ID of this instance
+ /// </summary>
+ public PlatformID Platform
+ {
+ get { return _platform; }
+ }
+
+ /// <summary>
+ /// Get the Version of this instance
+ /// </summary>
+ public Version Version
+ {
+ get { return _version; }
+ }
+
+ /// <summary>
+ /// Get the Product Type of this instance
+ /// </summary>
+ public ProductType Product
+ {
+ get { return _product; }
+ }
+
+ /// <summary>
+ /// Return true if this is a windows platform
+ /// </summary>
+ public bool IsWindows
+ {
+ get
+ {
+ return _platform == PlatformID.Win32NT
+ || _platform == PlatformID.Win32Windows
+ || _platform == PlatformID.Win32S
+ || _platform == PlatformID.WinCE;
+ }
+ }
+
+ /// <summary>
+ /// Return true if this is a Unix or Linux platform
+ /// </summary>
+ public bool IsUnix
+ {
+ get
+ {
+ return _platform == UnixPlatformID_Microsoft
+ || _platform == UnixPlatformID_Mono;
+ }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Win32S
+ /// </summary>
+ public bool IsWin32S
+ {
+ get { return _platform == PlatformID.Win32S; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Win32Windows
+ /// </summary>
+ public bool IsWin32Windows
+ {
+ get { return _platform == PlatformID.Win32Windows; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Win32NT
+ /// </summary>
+ public bool IsWin32NT
+ {
+ get { return _platform == PlatformID.Win32NT; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows CE
+ /// </summary>
+ public bool IsWinCE
+ {
+ get { return _platform == PlatformID.WinCE; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Xbox
+ /// </summary>
+ public bool IsXbox
+ {
+ get { return _platform == XBoxPlatformID; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is MacOSX
+ /// </summary>
+ public bool IsMacOSX
+ {
+ get { return _platform == MacOSXPlatformID; }
+ }
+
+#if !NETCF && !SILVERLIGHT
+ [DllImport("libc")]
+ static extern int uname(IntPtr buf);
+
+ static bool CheckIfIsMacOSX(PlatformID platform)
+ {
+ if (platform == PlatformID.MacOSX)
+ return true;
+
+ if (platform != PlatformID.Unix)
+ return false;
+
+ IntPtr buf = Marshal.AllocHGlobal(8192);
+ bool isMacOSX = false;
+ if (uname(buf) == 0)
+ {
+ string os = Marshal.PtrToStringAnsi(buf);
+ isMacOSX = os.Equals("Darwin");
+ }
+ Marshal.FreeHGlobal(buf);
+ return isMacOSX;
+ }
+#endif
+
+ /// <summary>
+ /// Return true if the platform is Windows 95
+ /// </summary>
+ public bool IsWin95
+ {
+ get { return _platform == PlatformID.Win32Windows && _version.Major == 4 && _version.Minor == 0; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 98
+ /// </summary>
+ public bool IsWin98
+ {
+ get { return _platform == PlatformID.Win32Windows && _version.Major == 4 && _version.Minor == 10; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows ME
+ /// </summary>
+ public bool IsWinME
+ {
+ get { return _platform == PlatformID.Win32Windows && _version.Major == 4 && _version.Minor == 90; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is NT 3
+ /// </summary>
+ public bool IsNT3
+ {
+ get { return _platform == PlatformID.Win32NT && _version.Major == 3; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is NT 4
+ /// </summary>
+ public bool IsNT4
+ {
+ get { return _platform == PlatformID.Win32NT && _version.Major == 4; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is NT 5
+ /// </summary>
+ public bool IsNT5
+ {
+ get { return _platform == PlatformID.Win32NT && _version.Major == 5; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 2000
+ /// </summary>
+ public bool IsWin2K
+ {
+ get { return IsNT5 && _version.Minor == 0; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows XP
+ /// </summary>
+ public bool IsWinXP
+ {
+ get { return IsNT5 && (_version.Minor == 1 || _version.Minor == 2 && Product == ProductType.WorkStation); }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 2003 Server
+ /// </summary>
+ public bool IsWin2003Server
+ {
+ get { return IsNT5 && _version.Minor == 2 && Product == ProductType.Server; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is NT 6
+ /// </summary>
+ public bool IsNT6
+ {
+ get { return _platform == PlatformID.Win32NT && _version.Major == 6; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is NT 6.0
+ /// </summary>
+ public bool IsNT60
+ {
+ get { return IsNT6 && _version.Minor == 0; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is NT 6.1
+ /// </summary>
+ public bool IsNT61
+ {
+ get { return IsNT6 && _version.Minor == 1; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is NT 6.2
+ /// </summary>
+ public bool IsNT62
+ {
+ get { return IsNT6 && _version.Minor == 2; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is NT 6.3
+ /// </summary>
+ public bool IsNT63
+ {
+ get { return IsNT6 && _version.Minor == 3; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Vista
+ /// </summary>
+ public bool IsVista
+ {
+ get { return IsNT60 && Product == ProductType.WorkStation; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 2008 Server (original or R2)
+ /// </summary>
+ public bool IsWin2008Server
+ {
+ get { return IsWin2008ServerR1 || IsWin2008ServerR2; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 2008 Server (original)
+ /// </summary>
+ public bool IsWin2008ServerR1
+ {
+ get { return IsNT60 && Product == ProductType.Server; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 2008 Server R2
+ /// </summary>
+ public bool IsWin2008ServerR2
+ {
+ get { return IsNT61 && Product == ProductType.Server; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 2012 Server (original or R2)
+ /// </summary>
+ public bool IsWin2012Server
+ {
+ get { return IsWin2012ServerR1 || IsWin2012ServerR2; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 2012 Server (original)
+ /// </summary>
+ public bool IsWin2012ServerR1
+ {
+ get { return IsNT62 && Product == ProductType.Server; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 2012 Server R2
+ /// </summary>
+ public bool IsWin2012ServerR2
+ {
+ get { return IsNT63 && Product == ProductType.Server; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 7
+ /// </summary>
+ public bool IsWindows7
+ {
+ get { return IsNT61 && Product == ProductType.WorkStation; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 8
+ /// </summary>
+ public bool IsWindows8
+ {
+ get { return IsNT62 && Product == ProductType.WorkStation; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 8.1
+ /// </summary>
+ public bool IsWindows81
+ {
+ get { return IsNT63 && Product == ProductType.WorkStation; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows 10
+ /// </summary>
+ public bool IsWindows10
+ {
+ get { return _platform == PlatformID.Win32NT && _version.Major == 10 && Product == ProductType.WorkStation; }
+ }
+
+ /// <summary>
+ /// Return true if the platform is Windows Server. This is named Windows
+ /// Server 10 to distinguish it from previous versions of Windows Server.
+ /// </summary>
+ public bool IsWindowsServer10
+ {
+ get { return _platform == PlatformID.Win32NT && _version.Major == 10 && Product == ProductType.Server; }
+ }
+ }
+}
+#endif
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+using System.IO;
+using NUnit.Framework.TUnit;
+
+#if PORTABLE
+using System.Linq;
+#endif
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// The ParameterWrapper class wraps a ParameterInfo so that it may
+ /// be used in a platform-independent manner.
+ /// </summary>
+ public class ParameterWrapper : IParameterInfo
+ {
+ /// <summary>
+ /// Construct a ParameterWrapper for a given method and parameter
+ /// </summary>
+ /// <param name="method"></param>
+ /// <param name="parameterInfo"></param>
+ public ParameterWrapper(IMethodInfo method, ParameterInfo parameterInfo)
+ {
+ Method = method;
+ ParameterInfo = parameterInfo;
+ }
+
+ #region Properties
+
+#if !NETCF
+ /// <summary>
+ /// Gets a value indicating whether the parameter is optional
+ /// </summary>
+ public bool IsOptional
+ {
+ get { return ParameterInfo.IsOptional; }
+ }
+#endif
+
+ /// <summary>
+ /// Gets an IMethodInfo representing the method for which this is a parameter.
+ /// </summary>
+ public IMethodInfo Method { get; private set; }
+
+ /// <summary>
+ /// Gets the underlying ParameterInfo
+ /// </summary>
+ public ParameterInfo ParameterInfo { get; private set; }
+
+ /// <summary>
+ /// Gets the Type of the parameter
+ /// </summary>
+ public Type ParameterType
+ {
+ get { return ParameterInfo.ParameterType; }
+ }
+
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Returns an array of custom attributes of the specified type applied to this method
+ /// </summary>
+ public T[] GetCustomAttributes<T>(bool inherit) where T : class
+ {
+#if PORTABLE
+ var allAttributes = ParameterInfo.GetCustomAttributes();
+ List<string> attributeDic = new List<string>();
+ foreach (Attribute atb in allAttributes)
+ {
+ attributeDic.Add(atb.GetType().FullName);
+ }
+ var assembly = ParameterInfo.ParameterType.GetTypeInfo().Assembly;
+ List<T> objects = new List<T>();
+
+ string path = System.IO.Path.GetDirectoryName(assembly.Location);
+ if (!Directory.Exists(path))
+ {
+ TLogger.WriteError(TLogger.ExceptionTag, "" + path + " - not a directory");
+ return objects.ToArray();
+ }
+ foreach (var assemblyPath in Directory.GetFiles(path, "*.Tests.dll"))
+ {
+ IEnumerable<Type> types;
+ try
+ {
+ Assembly please = AssemblyHelper.Load(assemblyPath);
+ if (please == null) continue;
+ types = please.GetTypes().Where(p => !p.GetTypeInfo().IsAbstract && p.GetTypeInfo().IsClass && p.GetTypeInfo().ImplementedInterfaces.Contains(typeof(T)));
+ }
+ catch (Exception)
+ {
+ //TLogger.Write(TLogger.ExceptionTag, ex.ToString());
+ continue;
+ }
+ for (int i = 0; i < types.Count(); i++)
+ {
+ try
+ {
+ if (attributeDic.Contains(types.ElementAt(i).FullName))
+ {
+ objects.Add((T)Activator.CreateInstance(types.ElementAt(i)));
+ }
+ }
+ catch (Exception)
+ {
+ //TLogger.Write(TLogger.ExceptionTag, ex.ToString());
+ }
+ }
+ }
+
+ return objects.ToArray();
+#else
+ return (T[])ParameterInfo.GetCustomAttributes(typeof(T), inherit);
+#endif
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether one or more attributes of the specified type are defined on the parameter.
+ /// </summary>
+ public bool IsDefined<T>(bool inherit)
+ {
+#if PORTABLE
+ return ParameterInfo.GetCustomAttributes(inherit).Any(a => typeof(T).IsAssignableFrom(a.GetType()));
+#else
+ return ParameterInfo.IsDefined(typeof(T), inherit);
+#endif
+ }
+
+ #endregion
+
+ #region extra
+ private string GetAssemblyName(string assemblyFullPath)
+ {
+
+ string[] delimiter1 = { "\\" };
+ string[] delimiter2 = { "/" };
+ string[] delimiterDot = { "." };
+ string[] strAry;
+ string returnValue = "";
+ try
+ {
+ strAry = assemblyFullPath.Split(delimiter1, StringSplitOptions.None);
+
+ if (strAry.Length < 2)
+ strAry = assemblyFullPath.Split(delimiter2, StringSplitOptions.None);
+
+ foreach (string str in strAry)
+ {
+ if (str.Contains("Tests.dll"))
+ {
+ string[] strSplit = str.Split(delimiterDot, StringSplitOptions.None);
+ returnValue = strSplit[0];
+ // LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, "check : "+ returnValue);
+ break;
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, e.ToString());
+ }
+
+ return returnValue;
+ }
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007-2016 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !PORTABLE
+using System;
+using System.Linq;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// PlatformHelper class is used by the PlatformAttribute class to
+ /// determine whether a platform is supported.
+ /// </summary>
+ public class PlatformHelper
+ {
+ private readonly OSPlatform _os;
+ private readonly RuntimeFramework _rt;
+
+ // Set whenever we fail to support a list of platforms
+ private string _reason = string.Empty;
+
+ const string CommonOSPlatforms =
+ "Win,Win32,Win32S,Win32NT,Win32Windows,WinCE,Win95,Win98,WinMe,NT3,NT4,NT5,NT6," +
+ "Win2008Server,Win2008ServerR2,Win2012Server,Win2012ServerR2," +
+ "Win2K,WinXP,Win2003Server,Vista,Win7,Windows7,Win8,Windows8,"+
+ "Win8.1,Windows8.1,Win10,Windows10,WindowsServer10,Unix,Linux";
+
+ /// <summary>
+ /// Comma-delimited list of all supported OS platform constants
+ /// </summary>
+#if NETCF
+ public const string OSPlatforms = CommonOSPlatforms;
+#else
+ public const string OSPlatforms = CommonOSPlatforms + ",Xbox,MacOSX";
+#endif
+
+ /// <summary>
+ /// Comma-delimited list of all supported Runtime platform constants
+ /// </summary>
+ public static readonly string RuntimePlatforms =
+ "Net,NetCF,SSCLI,Rotor,Mono,MonoTouch";
+
+ /// <summary>
+ /// Default constructor uses the operating system and
+ /// common language runtime of the system.
+ /// </summary>
+ public PlatformHelper()
+ {
+ _os = OSPlatform.CurrentPlatform;
+ _rt = RuntimeFramework.CurrentFramework;
+ }
+
+ /// <summary>
+ /// Construct a PlatformHelper for a particular operating
+ /// system and common language runtime. Used in testing.
+ /// </summary>
+ /// <param name="os">OperatingSystem to be used</param>
+ /// <param name="rt">RuntimeFramework to be used</param>
+ public PlatformHelper( OSPlatform os, RuntimeFramework rt )
+ {
+ _os = os;
+ _rt = rt;
+ }
+
+ /// <summary>
+ /// Test to determine if one of a collection of platforms
+ /// is being used currently.
+ /// </summary>
+ /// <param name="platforms"></param>
+ /// <returns></returns>
+ public bool IsPlatformSupported( string[] platforms )
+ {
+ return platforms.Any( IsPlatformSupported );
+ }
+
+ /// <summary>
+ /// Tests to determine if the current platform is supported
+ /// based on a platform attribute.
+ /// </summary>
+ /// <param name="platformAttribute">The attribute to examine</param>
+ /// <returns></returns>
+ public bool IsPlatformSupported( PlatformAttribute platformAttribute )
+ {
+ string include = platformAttribute.Include;
+ string exclude = platformAttribute.Exclude;
+
+ return IsPlatformSupported( include, exclude );
+ }
+
+ /// <summary>
+ /// Tests to determine if the current platform is supported
+ /// based on a platform attribute.
+ /// </summary>
+ /// <param name="testCaseAttribute">The attribute to examine</param>
+ /// <returns></returns>
+ public bool IsPlatformSupported(TestCaseAttribute testCaseAttribute)
+ {
+ string include = testCaseAttribute.IncludePlatform;
+ string exclude = testCaseAttribute.ExcludePlatform;
+
+ return IsPlatformSupported(include, exclude);
+ }
+
+ private bool IsPlatformSupported(string include, string exclude)
+ {
+ try
+ {
+ if (include != null && !IsPlatformSupported(include))
+ {
+ _reason = string.Format("Only supported on {0}", include);
+ return false;
+ }
+
+ if (exclude != null && IsPlatformSupported(exclude))
+ {
+ _reason = string.Format("Not supported on {0}", exclude);
+ return false;
+ }
+ }
+ catch (Exception ex)
+ {
+ _reason = ex.Message;
+ return false;
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Test to determine if the a particular platform or comma-
+ /// delimited set of platforms is in use.
+ /// </summary>
+ /// <param name="platform">Name of the platform or comma-separated list of platform ids</param>
+ /// <returns>True if the platform is in use on the system</returns>
+ public bool IsPlatformSupported( string platform )
+ {
+ if ( platform.IndexOf( ',' ) >= 0 )
+ return IsPlatformSupported( platform.Split(',') );
+
+ string platformName = platform.Trim();
+ bool isSupported;
+
+// string versionSpecification = null;
+//
+// string[] parts = platformName.Split( new char[] { '-' } );
+// if ( parts.Length == 2 )
+// {
+// platformName = parts[0];
+// versionSpecification = parts[1];
+// }
+
+ switch( platformName.ToUpper() )
+ {
+ case "WIN":
+ case "WIN32":
+ isSupported = _os.IsWindows;
+ break;
+ case "WIN32S":
+ isSupported = _os.IsWin32S;
+ break;
+ case "WIN32WINDOWS":
+ isSupported = _os.IsWin32Windows;
+ break;
+ case "WIN32NT":
+ isSupported = _os.IsWin32NT;
+ break;
+ case "WINCE":
+ isSupported = _os.IsWinCE;
+ break;
+ case "WIN95":
+ isSupported = _os.IsWin95;
+ break;
+ case "WIN98":
+ isSupported = _os.IsWin98;
+ break;
+ case "WINME":
+ isSupported = _os.IsWinME;
+ break;
+ case "NT3":
+ isSupported = _os.IsNT3;
+ break;
+ case "NT4":
+ isSupported = _os.IsNT4;
+ break;
+ case "NT5":
+ isSupported = _os.IsNT5;
+ break;
+ case "WIN2K":
+ isSupported = _os.IsWin2K;
+ break;
+ case "WINXP":
+ isSupported = _os.IsWinXP;
+ break;
+ case "WIN2003SERVER":
+ isSupported = _os.IsWin2003Server;
+ break;
+ case "NT6":
+ isSupported = _os.IsNT6;
+ break;
+ case "VISTA":
+ isSupported = _os.IsVista;
+ break;
+ case "WIN2008SERVER":
+ isSupported = _os.IsWin2008Server;
+ break;
+ case "WIN2008SERVERR2":
+ isSupported = _os.IsWin2008ServerR2;
+ break;
+ case "WIN2012SERVER":
+ isSupported = _os.IsWin2012ServerR1 || _os.IsWin2012ServerR2;
+ break;
+ case "WIN2012SERVERR2":
+ isSupported = _os.IsWin2012ServerR2;
+ break;
+ case "WIN7":
+ case "WINDOWS7":
+ isSupported = _os.IsWindows7;
+ break;
+ case "WINDOWS8":
+ case "WIN8":
+ isSupported = _os.IsWindows8;
+ break;
+ case "WINDOWS8.1":
+ case "WIN8.1":
+ isSupported = _os.IsWindows81;
+ break;
+ case "WINDOWS10":
+ case "WIN10":
+ isSupported = _os.IsWindows10;
+ break;
+ case "WINDOWSSERVER10":
+ isSupported = _os.IsWindowsServer10;
+ break;
+ case "UNIX":
+ case "LINUX":
+ isSupported = _os.IsUnix;
+ break;
+ case "XBOX":
+ isSupported = _os.IsXbox;
+ break;
+ case "MACOSX":
+ isSupported = _os.IsMacOSX;
+ break;
+ // These bitness tests relate to the process, not the OS.
+ // We can't use Environment.Is64BitProcess because it's
+ // only supported in NET 4.0 and higher.
+ case "64-BIT":
+ case "64-BIT-PROCESS":
+ isSupported = IntPtr.Size == 8;
+ break;
+ case "32-BIT":
+ case "32-BIT-PROCESS":
+ isSupported = IntPtr.Size == 4;
+ break;
+
+#if NET_4_0 || NET_4_5
+ // We only support bitness tests of the OS in .NET 4.0 and up
+ case "64-BIT-OS":
+ isSupported = Environment.Is64BitOperatingSystem;
+ break;
+ case "32-BIT-OS":
+ isSupported = !Environment.Is64BitOperatingSystem;
+ break;
+#endif
+
+ default:
+ isSupported = IsRuntimeSupported(platformName);
+ break;
+ }
+
+ if (!isSupported)
+ _reason = "Only supported on " + platform;
+
+ return isSupported;
+ }
+
+ /// <summary>
+ /// Return the last failure reason. Results are not
+ /// defined if called before IsSupported( Attribute )
+ /// is called.
+ /// </summary>
+ public string Reason
+ {
+ get { return _reason; }
+ }
+
+ private bool IsRuntimeSupported(string platformName)
+ {
+ string versionSpecification = null;
+ string[] parts = platformName.Split('-');
+ if (parts.Length == 2)
+ {
+ platformName = parts[0];
+ versionSpecification = parts[1];
+ }
+
+ switch (platformName.ToUpper())
+ {
+ case "NET":
+ return IsRuntimeSupported(RuntimeType.Net, versionSpecification);
+
+ case "NETCF":
+ return IsRuntimeSupported(RuntimeType.NetCF, versionSpecification);
+
+ case "SSCLI":
+ case "ROTOR":
+ return IsRuntimeSupported(RuntimeType.SSCLI, versionSpecification);
+
+ case "MONO":
+ return IsRuntimeSupported(RuntimeType.Mono, versionSpecification);
+
+ case "SL":
+ case "SILVERLIGHT":
+ return IsRuntimeSupported(RuntimeType.Silverlight, versionSpecification);
+
+ case "MONOTOUCH":
+ return IsRuntimeSupported(RuntimeType.MonoTouch, versionSpecification);
+
+ default:
+ throw new ArgumentException("Invalid platform name", platformName);
+ }
+ }
+
+ private bool IsRuntimeSupported(RuntimeType runtime, string versionSpecification)
+ {
+ Version version = versionSpecification == null
+ ? RuntimeFramework.DefaultVersion
+ : new Version(versionSpecification);
+
+ RuntimeFramework target = new RuntimeFramework(runtime, version);
+
+ return _rt.Supports(target);
+ }
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// A PropertyBag represents a collection of name value pairs
+ /// that allows duplicate entries with the same key. Methods
+ /// are provided for adding a new pair as well as for setting
+ /// a key to a single value. All keys are strings but _values
+ /// may be of any type. Null _values are not permitted, since
+ /// a null entry represents the absence of the key.
+ /// </summary>
+ public class PropertyBag : IPropertyBag
+ {
+ private Dictionary<string, IList> inner = new Dictionary<string, IList>();
+
+ #region IPropertyBagMembers
+
+ /// <summary>
+ /// Adds a key/value pair to the property set
+ /// </summary>
+ /// <param name="key">The key</param>
+ /// <param name="value">The value</param>
+ public void Add(string key, object value)
+ {
+ IList list;
+ if (!inner.TryGetValue(key, out list))
+ {
+ list = new List<object>();
+ inner.Add(key, list);
+ }
+ list.Add(value);
+ }
+
+ /// <summary>
+ /// Sets the value for a key, removing any other
+ /// _values that are already in the property set.
+ /// </summary>
+ /// <param name="key"></param>
+ /// <param name="value"></param>
+ public void Set(string key, object value)
+ {
+ // Guard against mystery exceptions later!
+ Guard.ArgumentNotNull(key, "key");
+ Guard.ArgumentNotNull(value, "value");
+
+ IList list = new List<object>();
+ list.Add(value);
+ inner[key] = list;
+ }
+
+ /// <summary>
+ /// Gets a single value for a key, using the first
+ /// one if multiple _values are present and returning
+ /// null if the value is not found.
+ /// </summary>
+ /// <param name="key"></param>
+ /// <returns></returns>
+ public object Get(string key)
+ {
+ IList list;
+ return inner.TryGetValue(key, out list) && list.Count > 0
+ ? list[0]
+ : null;
+ }
+
+ /// <summary>
+ /// Gets a flag indicating whether the specified key has
+ /// any entries in the property set.
+ /// </summary>
+ /// <param name="key">The key to be checked</param>
+ /// <returns>
+ /// True if their are _values present, otherwise false
+ /// </returns>
+ public bool ContainsKey(string key)
+ {
+ return inner.ContainsKey(key);
+ }
+
+ /// <summary>
+ /// Gets a collection containing all the keys in the property set
+ /// </summary>
+ /// <value></value>
+ public ICollection<string> Keys
+ {
+ get { return inner.Keys; }
+ }
+
+ /// <summary>
+ /// Gets or sets the list of _values for a particular key
+ /// </summary>
+ public IList this[string key]
+ {
+ get
+ {
+ IList list;
+ if (!inner.TryGetValue(key, out list))
+ {
+ list = new List<object>();
+ inner.Add(key, list);
+ }
+ return list;
+ }
+ set
+ {
+ inner[key] = value;
+ }
+ }
+
+ #endregion
+
+ #region IXmlNodeBuilder Members
+
+ /// <summary>
+ /// Returns an XmlNode representating the current PropertyBag.
+ /// </summary>
+ /// <param name="recursive">Not used</param>
+ /// <returns>An XmlNode representing the PropertyBag</returns>
+ public TNode ToXml(bool recursive)
+ {
+ return AddToXml(new TNode("dummy"), recursive);
+ }
+
+ /// <summary>
+ /// Returns an XmlNode representing the PropertyBag after
+ /// adding it as a child of the supplied parent node.
+ /// </summary>
+ /// <param name="parentNode">The parent node.</param>
+ /// <param name="recursive">Not used</param>
+ /// <returns></returns>
+ public TNode AddToXml(TNode parentNode, bool recursive)
+ {
+ TNode properties = parentNode.AddElement("properties");
+
+ foreach (string key in Keys)
+ {
+ foreach (object value in this[key])
+ {
+ TNode prop = properties.AddElement("property");
+
+ // TODO: Format as string
+ prop.AddAttribute("name", key.ToString());
+ prop.AddAttribute("value", value.ToString());
+ }
+ }
+
+ return properties;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// The PropertyNames class provides static constants for the
+ /// standard property ids that NUnit uses on tests.
+ /// </summary>
+ public class PropertyNames
+ {
+ #region Internal Properties
+
+ /// <summary>
+ /// The FriendlyName of the AppDomain in which the assembly is running
+ /// </summary>
+ public const string AppDomain = "_APPDOMAIN";
+
+ /// <summary>
+ /// The selected strategy for joining parameter data into test cases
+ /// </summary>
+ public const string JoinType = "_JOINTYPE";
+
+ /// <summary>
+ /// The process ID of the executing assembly
+ /// </summary>
+ public const string ProcessID = "_PID";
+
+ /// <summary>
+ /// The stack trace from any data provider that threw
+ /// an exception.
+ /// </summary>
+ public const string ProviderStackTrace = "_PROVIDERSTACKTRACE";
+
+ /// <summary>
+ /// The reason a test was not run
+ /// </summary>
+ public const string SkipReason = "_SKIPREASON";
+
+ #endregion
+
+ #region Standard Properties
+
+ /// <summary>
+ /// The author of the tests
+ /// </summary>
+ public const string Author = "Author";
+
+ /// <summary>
+ /// The ApartmentState required for running the test
+ /// </summary>
+ public const string ApartmentState = "ApartmentState";
+
+ /// <summary>
+ /// The categories applying to a test
+ /// </summary>
+ public const string Category = "Category";
+
+ /// <summary>
+ /// The Description of a test
+ /// </summary>
+ public const string Description = "Description";
+
+ /// <summary>
+ /// The number of threads to be used in running tests
+ /// </summary>
+ public const string LevelOfParallelism = "LevelOfParallelism";
+
+ /// <summary>
+ /// The maximum time in ms, above which the test is considered to have failed
+ /// </summary>
+ public const string MaxTime = "MaxTime";
+
+ /// <summary>
+ /// The ParallelScope associated with a test
+ /// </summary>
+ public const string ParallelScope = "ParallelScope";
+
+ /// <summary>
+ /// The number of times the test should be repeated
+ /// </summary>
+ public const string RepeatCount = "Repeat";
+
+ /// <summary>
+ /// Indicates that the test should be run on a separate thread
+ /// </summary>
+ public const string RequiresThread = "RequiresThread";
+
+ /// <summary>
+ /// The culture to be set for a test
+ /// </summary>
+ public const string SetCulture = "SetCulture";
+
+ /// <summary>
+ /// The UI culture to be set for a test
+ /// </summary>
+ public const string SetUICulture = "SetUICulture";
+
+ /// <summary>
+ /// The type that is under test
+ /// </summary>
+ public const string TestOf = "TestOf";
+
+ /// <summary>
+ /// The timeout value for the test
+ /// </summary>
+ public const string Timeout = "Timeout";
+
+ /// <summary>
+ /// The test will be ignored until the given date
+ /// </summary>
+ public const string IgnoreUntilDate = "IgnoreUntilDate";
+
+ /// <summary>
+ /// The optional Order the test will run in
+ /// </summary>
+ public const string Order = "Order";
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2013-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Text;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// Randomizer returns a set of random _values in a repeatable
+ /// way, to allow re-running of tests if necessary. It extends
+ /// the .NET Random class, providing random values for a much
+ /// wider range of types.
+ ///
+ /// The class is used internally by the framework to generate
+ /// test case data and is also exposed for use by users through
+ /// the TestContext.Random property.
+ /// </summary>
+ /// <remarks>
+ /// For consistency with the underlying Random Type, methods
+ /// returning a single value use the prefix "Next..." Those
+ /// without an argument return a non-negative value up to
+ /// the full positive range of the Type. Overloads are provided
+ /// for specifying a maximum or a range. Methods that return
+ /// arrays or strings use the prefix "Get..." to avoid
+ /// confusion with the single-value methods.
+ /// </remarks>
+ public class Randomizer : Random
+ {
+ #region Static Members
+
+ // Static constructor initializes values
+ static Randomizer()
+ {
+ InitialSeed = new Random().Next();
+ Randomizers = new Dictionary<MemberInfo, Randomizer>();
+ }
+
+ // Static Random instance used exclusively for the generation
+ // of seed values for new Randomizers.
+ private static Random _seedGenerator;
+
+ /// <summary>
+ /// Initial seed used to create randomizers for this run
+ /// </summary>
+ public static int InitialSeed
+ {
+ get { return _initialSeed; }
+ set
+ {
+ _initialSeed = value;
+ // Setting or resetting the initial seed creates seed generator
+ _seedGenerator = new Random(_initialSeed);
+ }
+ }
+ private static int _initialSeed;
+
+ // Lookup Dictionary used to find randomizers for each member
+ private static Dictionary<MemberInfo, Randomizer> Randomizers;
+
+ /// <summary>
+ /// Get a Randomizer for a particular member, returning
+ /// one that has already been created if it exists.
+ /// This ensures that the same _values are generated
+ /// each time the tests are reloaded.
+ /// </summary>
+ public static Randomizer GetRandomizer(MemberInfo member)
+ {
+ if (Randomizers.ContainsKey(member))
+ return Randomizers[member];
+ else
+ {
+ var r = CreateRandomizer();
+ Randomizers[member] = r;
+ return r;
+ }
+ }
+
+
+ /// <summary>
+ /// Get a randomizer for a particular parameter, returning
+ /// one that has already been created if it exists.
+ /// This ensures that the same values are generated
+ /// each time the tests are reloaded.
+ /// </summary>
+ public static Randomizer GetRandomizer(ParameterInfo parameter)
+ {
+ return GetRandomizer(parameter.Member);
+ }
+
+ /// <summary>
+ /// Create a new Randomizer using the next seed
+ /// available to ensure that each randomizer gives
+ /// a unique sequence of values.
+ /// </summary>
+ /// <returns></returns>
+ public static Randomizer CreateRandomizer()
+ {
+ return new Randomizer(_seedGenerator.Next());
+ }
+
+ #endregion
+
+ #region Constructors
+
+ /// <summary>
+ /// Default constructor
+ /// </summary>
+ public Randomizer() { }
+
+ /// <summary>
+ /// Construct based on seed value
+ /// </summary>
+ /// <param name="seed"></param>
+ public Randomizer(int seed) : base(seed) { }
+
+ #endregion
+
+ #region Ints
+
+ // NOTE: Next(), Next(int max) and Next(int min, int max) are
+ // inherited from Random.
+
+ #endregion
+
+ #region Unsigned Ints
+
+ /// <summary>
+ /// Returns a random unsigned int.
+ /// </summary>
+ //[CLSCompliant(false)]
+ public uint NextUInt()
+ {
+ return NextUInt(0u, uint.MaxValue);
+ }
+
+ /// <summary>
+ /// Returns a random unsigned int less than the specified maximum.
+ /// </summary>
+ //[CLSCompliant(false)]
+ public uint NextUInt(uint max)
+ {
+ return NextUInt(0u, max);
+ }
+
+ /// <summary>
+ /// Returns a random unsigned int within a specified range.
+ /// </summary>
+ //[CLSCompliant(false)]
+ public uint NextUInt(uint min, uint max)
+ {
+ Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", "max");
+
+ if (min == max)
+ return min;
+
+ uint range = max - min;
+
+ // Avoid introduction of modulo bias
+ uint limit = uint.MaxValue - uint.MaxValue % range;
+ uint raw;
+ do
+ {
+ raw = RawUInt();
+ }
+ while (raw > limit);
+
+ return unchecked(raw % range + min);
+ }
+
+ #endregion
+
+ #region Shorts
+
+ /// <summary>
+ /// Returns a non-negative random short.
+ /// </summary>
+ public short NextShort()
+ {
+ return NextShort(0, short.MaxValue);
+ }
+
+ /// <summary>
+ /// Returns a non-negative random short less than the specified maximum.
+ /// </summary>
+ public short NextShort(short max)
+ {
+ return NextShort((short)0, max);
+ }
+
+ /// <summary>
+ /// Returns a non-negative random short within a specified range.
+ /// </summary>
+ public short NextShort(short min, short max)
+ {
+ return (short)Next(min, max);
+ }
+
+ #endregion
+
+ #region Unsigned Shorts
+
+ /// <summary>
+ /// Returns a random unsigned short.
+ /// </summary>
+ //[CLSCompliant(false)]
+ public ushort NextUShort()
+ {
+ return NextUShort((ushort)0, ushort.MaxValue);
+ }
+
+ /// <summary>
+ /// Returns a random unsigned short less than the specified maximum.
+ /// </summary>
+ //[CLSCompliant(false)]
+ public ushort NextUShort(ushort max)
+ {
+ return NextUShort((ushort)0, max);
+ }
+
+ /// <summary>
+ /// Returns a random unsigned short within a specified range.
+ /// </summary>
+ //[CLSCompliant(false)]
+ public ushort NextUShort(ushort min, ushort max)
+ {
+ return (ushort)Next(min, max);
+ }
+
+ #endregion
+
+ #region Longs
+
+ /// <summary>
+ /// Returns a random long.
+ /// </summary>
+ public long NextLong()
+ {
+ return NextLong(0L, long.MaxValue);
+ }
+
+ /// <summary>
+ /// Returns a random long less than the specified maximum.
+ /// </summary>
+ public long NextLong(long max)
+ {
+ return NextLong(0L, max);
+ }
+
+ /// <summary>
+ /// Returns a non-negative random long within a specified range.
+ /// </summary>
+ public long NextLong(long min, long max)
+ {
+ Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", "max");
+
+ if (min == max)
+ return min;
+
+ ulong range = (ulong)(max - min);
+
+ // Avoid introduction of modulo bias
+ ulong limit = ulong.MaxValue - ulong.MaxValue % range;
+ ulong raw;
+ do
+ {
+ raw = RawULong();
+ }
+ while (raw > limit);
+
+ return (long)(raw % range + (ulong)min);
+ }
+
+ #endregion
+
+ #region Unsigned Longs
+
+ /// <summary>
+ /// Returns a random ulong.
+ /// </summary>
+ //[CLSCompliant(false)]
+ public ulong NextULong()
+ {
+ return NextULong(0ul, ulong.MaxValue);
+ }
+
+ /// <summary>
+ /// Returns a random ulong less than the specified maximum.
+ /// </summary>
+ //[CLSCompliant(false)]
+ public ulong NextULong(ulong max)
+ {
+ return NextULong(0ul, max);
+ }
+
+ /// <summary>
+ /// Returns a non-negative random long within a specified range.
+ /// </summary>
+ //[CLSCompliant(false)]
+ public ulong NextULong(ulong min, ulong max)
+ {
+ Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", "max");
+
+ ulong range = max - min;
+
+ if (range == 0)
+ return min;
+
+ // Avoid introduction of modulo bias
+ ulong limit = ulong.MaxValue - ulong.MaxValue % range;
+ ulong raw;
+ do
+ {
+ raw = RawULong();
+ }
+ while (raw > limit);
+
+ return unchecked(raw % range + min);
+ }
+
+ #endregion
+
+ #region Bytes
+
+ /// <summary>
+ /// Returns a random Byte
+ /// </summary>
+ public byte NextByte()
+ {
+ return NextByte((byte)0, Byte.MaxValue);
+ }
+
+ /// <summary>
+ /// Returns a random Byte less than the specified maximum.
+ /// </summary>
+ public byte NextByte(byte max)
+ {
+ return NextByte((byte)0, max);
+ }
+
+ /// <summary>
+ /// Returns a random Byte within a specified range
+ /// </summary>
+ public byte NextByte(byte min, byte max)
+ {
+ return (byte)Next(min, max);
+ }
+
+ #endregion
+
+ #region SBytes
+
+ /// <summary>
+ /// Returns a random SByte
+ /// </summary>
+ //[CLSCompliant(false)]
+ public sbyte NextSByte()
+ {
+ return NextSByte((sbyte)0, SByte.MaxValue);
+ }
+
+ /// <summary>
+ /// Returns a random sbyte less than the specified maximum.
+ /// </summary>
+ //[CLSCompliant(false)]
+ public sbyte NextSByte(sbyte max)
+ {
+ return NextSByte((sbyte)0, max);
+ }
+
+ /// <summary>
+ /// Returns a random sbyte within a specified range
+ /// </summary>
+ //[CLSCompliant(false)]
+ public sbyte NextSByte(sbyte min, sbyte max)
+ {
+ return (sbyte)Next(min, max);
+ }
+
+ #endregion
+
+ #region Bools
+
+ /// <summary>
+ /// Returns a random bool
+ /// </summary>
+ public bool NextBool()
+ {
+ return NextDouble() < 0.5;
+ }
+
+ /// <summary>
+ /// Returns a random bool based on the probablility a true result
+ /// </summary>
+ public bool NextBool(double probability)
+ {
+ Guard.ArgumentInRange(probability >= 0.0 && probability <= 1.0, "Probability must be from 0.0 to 1.0", "probability");
+
+ return NextDouble() < probability;
+ }
+
+ #endregion
+
+ #region Doubles
+
+ // NOTE: NextDouble() is inherited from Random.
+
+ /// <summary>
+ /// Returns a random double between 0.0 and the specified maximum.
+ /// </summary>
+ public double NextDouble(double max)
+ {
+ return NextDouble() * max;
+ }
+
+ /// <summary>
+ /// Returns a random double within a specified range.
+ /// </summary>
+ public double NextDouble(double min, double max)
+ {
+ Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", "max");
+
+ if (max == min)
+ return min;
+
+ double range = max - min;
+ return NextDouble() * range + min;
+ }
+
+ #endregion
+
+ #region Floats
+
+ /// <summary>
+ /// Returns a random float.
+ /// </summary>
+ public float NextFloat()
+ {
+ return (float)NextDouble();
+ }
+
+ /// <summary>
+ /// Returns a random float between 0.0 and the specified maximum.
+ /// </summary>
+ public float NextFloat(float max)
+ {
+ return (float)NextDouble(max);
+ }
+
+ /// <summary>
+ /// Returns a random float within a specified range.
+ /// </summary>
+ public float NextFloat(float min, float max)
+ {
+ return (float)NextDouble(min, max);
+ }
+
+ #endregion
+
+ #region Enums
+
+ /// <summary>
+ /// Returns a random enum value of the specified Type as an object.
+ /// </summary>
+ public object NextEnum(Type type)
+ {
+ Array enums = TypeHelper.GetEnumValues(type);
+ return enums.GetValue(Next(0, enums.Length));
+ }
+
+ /// <summary>
+ /// Returns a random enum value of the specified Type.
+ /// </summary>
+ public T NextEnum<T>()
+ {
+ return (T)NextEnum(typeof(T));
+ }
+
+ #endregion
+
+ #region String
+
+ /// <summary>
+ /// Default characters for random functions.
+ /// </summary>
+ /// <remarks>Default characters are the English alphabet (uppercase & lowercase), arabic numerals, and underscore</remarks>
+ public const string DefaultStringChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789_";
+
+ private const int DefaultStringLength = 25;
+
+ /// <summary>
+ /// Generate a random string based on the characters from the input string.
+ /// </summary>
+ /// <param name="outputLength">desired length of output string.</param>
+ /// <param name="allowedChars">string representing the set of characters from which to construct the resulting string</param>
+ /// <returns>A random string of arbitrary length</returns>
+ public string GetString(int outputLength, string allowedChars)
+ {
+
+ var sb = new StringBuilder(outputLength);
+
+ for (int i = 0; i < outputLength ; i++)
+ {
+ sb.Append(allowedChars[Next(0,allowedChars.Length)]);
+ }
+
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// Generate a random string based on the characters from the input string.
+ /// </summary>
+ /// <param name="outputLength">desired length of output string.</param>
+ /// <returns>A random string of arbitrary length</returns>
+ /// <remarks>Uses <see cref="DefaultStringChars">DefaultStringChars</see> as the input character set </remarks>
+ public string GetString(int outputLength)
+ {
+ return GetString(outputLength, DefaultStringChars);
+ }
+
+ /// <summary>
+ /// Generate a random string based on the characters from the input string.
+ /// </summary>
+ /// <returns>A random string of the default length</returns>
+ /// <remarks>Uses <see cref="DefaultStringChars">DefaultStringChars</see> as the input character set </remarks>
+ public string GetString()
+ {
+ return GetString(DefaultStringLength, DefaultStringChars);
+ }
+
+ #endregion
+
+ #region Decimal
+
+ // We treat decimal as an integral type for now.
+ // The scaling factor is always zero.
+
+ /// <summary>
+ /// Returns a random decimal.
+ /// </summary>
+ public decimal NextDecimal()
+ {
+ int low = Next(0, int.MaxValue);
+ int mid = Next(0, int.MaxValue);
+ int high = Next(0, int.MaxValue);
+ return new Decimal(low, mid, high, false, 0);
+ }
+
+ /// <summary>
+ /// Returns a random decimal between positive zero and the specified maximum.
+ /// </summary>
+ public decimal NextDecimal(decimal max)
+ {
+ return NextDecimal() % max;
+ }
+
+ /// <summary>
+ /// Returns a random decimal within a specified range, which is not
+ /// permitted to exceed decimal.MaxVal in the current implementation.
+ /// </summary>
+ /// <remarks>
+ /// A limitation of this implementation is that the range from min
+ /// to max must not exceed decimal.MaxVal.
+ /// </remarks>
+ public decimal NextDecimal(decimal min, decimal max)
+ {
+ Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", "max");
+
+ // Check that the range is not greater than MaxValue without
+ // first calculating it, since this would cause overflow
+ Guard.ArgumentValid(max < 0M == min < 0M || min + decimal.MaxValue >= max,
+ "Range too great for decimal data, use double range", "max");
+
+ if (min == max)
+ return min;
+
+ decimal range = max - min;
+
+ // Avoid introduction of modulo bias
+ decimal limit = decimal.MaxValue - decimal.MaxValue % range;
+ decimal raw;
+ do
+ {
+ raw = NextDecimal();
+ }
+ while (raw > limit);
+
+ return unchecked(raw % range + min);
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ private uint RawUInt()
+ {
+ var buffer = new byte[sizeof(uint)];
+ NextBytes(buffer);
+ return BitConverter.ToUInt32(buffer, 0);
+ }
+
+ private uint RawUShort()
+ {
+ var buffer = new byte[sizeof(uint)];
+ NextBytes(buffer);
+ return BitConverter.ToUInt32(buffer, 0);
+ }
+
+ private ulong RawULong()
+ {
+ var buffer = new byte[sizeof(ulong)];
+ NextBytes(buffer);
+ return BitConverter.ToUInt64(buffer, 0);
+ }
+
+ private long RawLong()
+ {
+ var buffer = new byte[sizeof(long)];
+ NextBytes(buffer);
+ return BitConverter.ToInt64(buffer, 0);
+ }
+
+ private decimal RawDecimal()
+ {
+ int low = Next(0, int.MaxValue);
+ int mid = Next(0, int.MaxValue);
+ int hi = Next(0, int.MaxValue);
+ bool isNegative = NextBool();
+ byte scale = NextByte(29);
+ return new Decimal(low, mid, hi, isNegative, scale);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007-2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+
+#if PORTABLE
+using System.Linq;
+#endif
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// Helper methods for inspecting a type by reflection.
+ ///
+ /// Many of these methods take ICustomAttributeProvider as an
+ /// argument to avoid duplication, even though certain attributes can
+ /// only appear on specific types of members, like MethodInfo or Type.
+ ///
+ /// In the case where a type is being examined for the presence of
+ /// an attribute, interface or named member, the Reflect methods
+ /// operate with the full name of the member being sought. This
+ /// removes the necessity of the caller having a reference to the
+ /// assembly that defines the item being sought and allows the
+ /// NUnit core to inspect assemblies that reference an older
+ /// version of the NUnit framework.
+ /// </summary>
+ public static class Reflect
+ {
+ private static readonly BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
+
+ // A zero-length Type array - not provided by System.Type for all CLR versions we support.
+ private static readonly Type[] EmptyTypes = new Type[0];
+
+ #region Get Methods of a type
+
+ /// <summary>
+ /// Examine a fixture type and return an array of methods having a
+ /// particular attribute. The array is order with base methods first.
+ /// </summary>
+ /// <param name="fixtureType">The type to examine</param>
+ /// <param name="attributeType">The attribute Type to look for</param>
+ /// <param name="inherit">Specifies whether to search the fixture type inheritance chain</param>
+ /// <returns>The array of methods found</returns>
+ public static MethodInfo[] GetMethodsWithAttribute(Type fixtureType, Type attributeType, bool inherit)
+ {
+ List<MethodInfo> list = new List<MethodInfo>();
+
+#if NETCF
+ if (fixtureType.IsGenericTypeDefinition)
+ {
+ var genArgs = fixtureType.GetGenericArguments();
+ Type[] args = new Type[genArgs.Length];
+ for (int ix = 0; ix < genArgs.Length; ++ix)
+ {
+ args[ix] = typeof(object);
+ }
+
+ fixtureType = fixtureType.MakeGenericType(args);
+ }
+#endif
+
+ var flags = AllMembers | (inherit ? BindingFlags.FlattenHierarchy : BindingFlags.DeclaredOnly);
+ foreach (MethodInfo method in fixtureType.GetMethods(flags))
+ {
+ if (method.IsDefined(attributeType, inherit))
+ list.Add(method);
+ }
+
+ list.Sort(new BaseTypesFirstComparer());
+
+ return list.ToArray();
+ }
+
+ private class BaseTypesFirstComparer : IComparer<MethodInfo>
+ {
+ public int Compare(MethodInfo m1, MethodInfo m2)
+ {
+ if (m1 == null || m2 == null) return 0;
+
+ Type m1Type = m1.DeclaringType;
+ Type m2Type = m2.DeclaringType;
+
+ if ( m1Type == m2Type ) return 0;
+ if ( m1Type.IsAssignableFrom(m2Type) ) return -1;
+
+ return 1;
+ }
+ }
+
+ /// <summary>
+ /// Examine a fixture type and return true if it has a method with
+ /// a particular attribute.
+ /// </summary>
+ /// <param name="fixtureType">The type to examine</param>
+ /// <param name="attributeType">The attribute Type to look for</param>
+ /// <returns>True if found, otherwise false</returns>
+ public static bool HasMethodWithAttribute(Type fixtureType, Type attributeType)
+ {
+#if PORTABLE
+ return fixtureType.GetMethods(AllMembers | BindingFlags.FlattenHierarchy)
+ .Any(m => m.GetCustomAttributes(false).Any(a => attributeType.IsAssignableFrom(a.GetType())));
+#else
+
+#if NETCF
+ if (fixtureType.ContainsGenericParameters)
+ return false;
+#endif
+ foreach (MethodInfo method in fixtureType.GetMethods(AllMembers | BindingFlags.FlattenHierarchy))
+ {
+ if (method.IsDefined(attributeType, false))
+ return true;
+ }
+ return false;
+#endif
+ }
+
+ #endregion
+
+ #region Invoke Constructors
+
+ /// <summary>
+ /// Invoke the default constructor on a Type
+ /// </summary>
+ /// <param name="type">The Type to be constructed</param>
+ /// <returns>An instance of the Type</returns>
+ public static object Construct(Type type)
+ {
+ ConstructorInfo ctor = type.GetConstructor(EmptyTypes);
+ if (ctor == null)
+ throw new InvalidTestFixtureException(type.FullName + " does not have a default constructor");
+
+ return ctor.Invoke(null);
+ }
+
+ /// <summary>
+ /// Invoke a constructor on a Type with arguments
+ /// </summary>
+ /// <param name="type">The Type to be constructed</param>
+ /// <param name="arguments">Arguments to the constructor</param>
+ /// <returns>An instance of the Type</returns>
+ public static object Construct(Type type, object[] arguments)
+ {
+ if (arguments == null) return Construct(type);
+
+ Type[] argTypes = GetTypeArray(arguments);
+ ITypeInfo typeInfo = new TypeWrapper(type);
+ ConstructorInfo ctor = typeInfo.GetConstructor(argTypes);
+ if (ctor == null)
+ throw new InvalidTestFixtureException(type.FullName + " does not have a suitable constructor");
+
+ return ctor.Invoke(arguments);
+ }
+
+ /// <summary>
+ /// Returns an array of types from an array of objects.
+ /// Used because the compact framework doesn't support
+ /// Type.GetTypeArray()
+ /// </summary>
+ /// <param name="objects">An array of objects</param>
+ /// <returns>An array of Types</returns>
+ internal static Type[] GetTypeArray(object[] objects)
+ {
+ Type[] types = new Type[objects.Length];
+ int index = 0;
+ foreach (object o in objects)
+ {
+ // NUnitNullType is a marker to indicate null since we can't do typeof(null) or null.GetType()
+ types[index++] = o == null ? typeof(NUnitNullType) : o.GetType();
+ }
+ return types;
+ }
+
+ #endregion
+
+ #region Invoke Methods
+
+ /// <summary>
+ /// Invoke a parameterless method returning void on an object.
+ /// </summary>
+ /// <param name="method">A MethodInfo for the method to be invoked</param>
+ /// <param name="fixture">The object on which to invoke the method</param>
+ public static object InvokeMethod( MethodInfo method, object fixture )
+ {
+ return InvokeMethod(method, fixture, null);
+ }
+
+ /// <summary>
+ /// Invoke a method, converting any TargetInvocationException to an NUnitException.
+ /// </summary>
+ /// <param name="method">A MethodInfo for the method to be invoked</param>
+ /// <param name="fixture">The object on which to invoke the method</param>
+ /// <param name="args">The argument list for the method</param>
+ /// <returns>The return value from the invoked method</returns>
+ public static object InvokeMethod( MethodInfo method, object fixture, params object[] args )
+ {
+ if(method != null)
+ {
+ try
+ {
+ return method.Invoke(fixture, args);
+ }
+#if !PORTABLE
+ catch (System.Threading.ThreadAbortException)
+ {
+ // No need to wrap or rethrow ThreadAbortException
+ return null;
+ }
+#endif
+ catch (TargetInvocationException e)
+ {
+ throw new NUnitException("Rethrown", e.InnerException);
+ }
+ catch (Exception e)
+ {
+ throw new NUnitException("Rethrown", e);
+ }
+ }
+
+ return null;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+#if PARALLEL
+using System.Collections.Concurrent;
+#endif
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// Represents the result of running a single test case.
+ /// </summary>
+ public class TestCaseResult : TestResult
+ {
+ /// <summary>
+ /// Construct a TestCaseResult based on a TestMethod
+ /// </summary>
+ /// <param name="test">A TestMethod to which the result applies.</param>
+ public TestCaseResult(TestMethod test) : base(test) { }
+
+ #region Overrides
+
+ /// <summary>
+ /// Gets the number of test cases that failed
+ /// when running the test and all its children.
+ /// </summary>
+ public override int FailCount
+ {
+ get { return ResultState.Status == TestStatus.Failed ? 1 : 0; }
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that passed
+ /// when running the test and all its children.
+ /// </summary>
+ public override int PassCount
+ {
+ get { return ResultState.Status == TestStatus.Passed ? 1 : 0; }
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that were skipped
+ /// when running the test and all its children.
+ /// </summary>
+ public override int SkipCount
+ {
+ get { return ResultState.Status == TestStatus.Skipped ? 1 : 0; }
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that were inconclusive
+ /// when running the test and all its children.
+ /// </summary>
+ public override int InconclusiveCount
+ {
+ get { return ResultState.Status == TestStatus.Inconclusive ? 1 : 0; }
+ }
+
+ /// <summary>
+ /// Indicates whether this result has any child results.
+ /// </summary>
+ public override bool HasChildren
+ {
+ get { return false; }
+ }
+
+ /// <summary>
+ /// Gets the collection of child results.
+ /// </summary>
+ public override IEnumerable<ITestResult> Children
+ {
+ get { return new ITestResult[0]; }
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010-2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+#if PARALLEL
+using System.Collections.Concurrent;
+#endif
+using System.Globalization;
+using System.IO;
+using System.Text;
+#if NETCF || NET_2_0
+using NUnit.Compatibility;
+#endif
+using System.Threading;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// The TestResult class represents the result of a test.
+ /// </summary>
+ public abstract class TestResult : ITestResult
+ {
+ #region Fields
+
+ /// <summary>
+ /// Error message for when child tests have errors
+ /// </summary>
+ internal static readonly string CHILD_ERRORS_MESSAGE = "One or more child tests had errors";
+
+ /// <summary>
+ /// Error message for when child tests are ignored
+ /// </summary>
+ internal static readonly string CHILD_IGNORE_MESSAGE = "One or more child tests were ignored";
+
+ /// <summary>
+ /// The minimum duration for tests
+ /// </summary>
+ internal const double MIN_DURATION = 0.000001d;
+
+ // static Logger log = InternalTrace.GetLogger("TestResult");
+
+ private StringBuilder _output = new StringBuilder();
+ private double _duration;
+
+ /// <summary>
+ /// Aggregate assertion count
+ /// </summary>
+ protected int InternalAssertCount;
+
+ private ResultState _resultState;
+ private string _message;
+ private string _stackTrace;
+
+#if PARALLEL
+ /// <summary>
+ /// ReaderWriterLock
+ /// </summary>
+#if NET_2_0
+ protected ReaderWriterLock RwLock = new ReaderWriterLock();
+#elif NETCF
+ protected ReaderWriterLockSlim RwLock = new ReaderWriterLockSlim();
+#else
+ protected ReaderWriterLockSlim RwLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
+#endif
+#endif
+
+ #endregion
+
+ #region Constructor
+
+ /// <summary>
+ /// Construct a test result given a Test
+ /// </summary>
+ /// <param name="test">The test to be used</param>
+ public TestResult(ITest test)
+ {
+ Test = test;
+ ResultState = ResultState.Inconclusive;
+
+#if PORTABLE || SILVERLIGHT
+ OutWriter = new StringWriter(_output);
+#else
+ OutWriter = TextWriter.Synchronized(new StringWriter(_output));
+#endif
+ }
+
+ #endregion
+
+ #region ITestResult Members
+
+ /// <summary>
+ /// Gets the test with which this result is associated.
+ /// </summary>
+ public ITest Test { get; private set; }
+
+ /// <summary>
+ /// Gets the ResultState of the test result, which
+ /// indicates the success or failure of the test.
+ /// </summary>
+ public ResultState ResultState
+ {
+ get
+ {
+#if PARALLEL
+ RwLock.EnterReadLock();
+#endif
+ try
+ {
+ return _resultState;
+ }
+ finally
+ {
+#if PARALLEL
+ RwLock.ExitReadLock();
+#endif
+ }
+ }
+ private set { _resultState = value; }
+ }
+
+ /// <summary>
+ /// Gets the name of the test result
+ /// </summary>
+ public virtual string Name
+ {
+ get { return Test.Name; }
+ }
+
+ /// <summary>
+ /// Gets the full name of the test result
+ /// </summary>
+ public virtual string FullName
+ {
+ get { return Test.FullName; }
+ }
+
+ /// <summary>
+ /// Gets or sets the elapsed time for running the test in seconds
+ /// </summary>
+ public double Duration
+ {
+ get { return _duration; }
+ set { _duration = value >= MIN_DURATION ? value : MIN_DURATION; }
+ }
+
+ /// <summary>
+ /// Gets or sets the time the test started running.
+ /// </summary>
+ public DateTime StartTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time the test finished running.
+ /// </summary>
+ public DateTime EndTime { get; set; }
+
+ /// <summary>
+ /// Gets the message associated with a test
+ /// failure or with not running the test
+ /// </summary>
+ public string Message
+ {
+ get
+ {
+#if PARALLEL
+ RwLock.EnterReadLock();
+#endif
+ try
+ {
+ return _message;
+ }
+ finally
+ {
+#if PARALLEL
+ RwLock.ExitReadLock();
+#endif
+ }
+
+ }
+ private set
+ {
+ _message = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets any stacktrace associated with an
+ /// error or failure.
+ /// </summary>
+ public virtual string StackTrace
+ {
+ get
+ {
+#if PARALLEL
+ RwLock.EnterReadLock();
+#endif
+ try
+ {
+ return _stackTrace;
+ }
+ finally
+ {
+#if PARALLEL
+ RwLock.ExitReadLock();
+#endif
+ }
+ }
+
+ private set
+ {
+ _stackTrace = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the count of asserts executed
+ /// when running the test.
+ /// </summary>
+ public int AssertCount
+ {
+ get
+ {
+#if PARALLEL
+ RwLock.EnterReadLock();
+#endif
+ try
+ {
+ return InternalAssertCount;
+ }
+ finally
+ {
+#if PARALLEL
+ RwLock.ExitReadLock ();
+#endif
+ }
+ }
+
+ internal set
+ {
+ InternalAssertCount = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that failed
+ /// when running the test and all its children.
+ /// </summary>
+ public abstract int FailCount { get; }
+
+ /// <summary>
+ /// Gets the number of test cases that passed
+ /// when running the test and all its children.
+ /// </summary>
+ public abstract int PassCount { get; }
+
+ /// <summary>
+ /// Gets the number of test cases that were skipped
+ /// when running the test and all its children.
+ /// </summary>
+ public abstract int SkipCount { get; }
+
+ /// <summary>
+ /// Gets the number of test cases that were inconclusive
+ /// when running the test and all its children.
+ /// </summary>
+ public abstract int InconclusiveCount { get; }
+
+ /// <summary>
+ /// Indicates whether this result has any child results.
+ /// </summary>
+ public abstract bool HasChildren { get; }
+
+ /// <summary>
+ /// Gets the collection of child results.
+ /// </summary>
+ public abstract IEnumerable<ITestResult> Children { get; }
+
+ /// <summary>
+ /// Gets a TextWriter, which will write output to be included in the result.
+ /// </summary>
+ public TextWriter OutWriter { get; private set; }
+
+ /// <summary>
+ /// Gets any text output written to this result.
+ /// </summary>
+ public string Output
+ {
+ get { return _output.ToString(); }
+ }
+
+ #endregion
+
+ #region IXmlNodeBuilder Members
+
+ /// <summary>
+ /// Returns the Xml representation of the result.
+ /// </summary>
+ /// <param name="recursive">If true, descendant results are included</param>
+ /// <returns>An XmlNode representing the result</returns>
+ public TNode ToXml(bool recursive)
+ {
+ return AddToXml(new TNode("dummy"), recursive);
+ }
+
+ /// <summary>
+ /// Adds the XML representation of the result as a child of the
+ /// supplied parent node..
+ /// </summary>
+ /// <param name="parentNode">The parent node.</param>
+ /// <param name="recursive">If true, descendant results are included</param>
+ /// <returns></returns>
+ public virtual TNode AddToXml(TNode parentNode, bool recursive)
+ {
+ // A result node looks like a test node with extra info added
+ TNode thisNode = Test.AddToXml(parentNode, false);
+
+ thisNode.AddAttribute("result", ResultState.Status.ToString());
+ if (ResultState.Label != string.Empty) // && ResultState.Label != ResultState.Status.ToString())
+ thisNode.AddAttribute("label", ResultState.Label);
+ if (ResultState.Site != FailureSite.Test)
+ thisNode.AddAttribute("site", ResultState.Site.ToString());
+
+ thisNode.AddAttribute("start-time", StartTime.ToString("u"));
+ thisNode.AddAttribute("end-time", EndTime.ToString("u"));
+ thisNode.AddAttribute("duration", Duration.ToString("0.000000", NumberFormatInfo.InvariantInfo));
+
+ if (Test is TestSuite)
+ {
+ thisNode.AddAttribute("total", (PassCount + FailCount + SkipCount + InconclusiveCount).ToString());
+ thisNode.AddAttribute("passed", PassCount.ToString());
+ thisNode.AddAttribute("failed", FailCount.ToString());
+ thisNode.AddAttribute("inconclusive", InconclusiveCount.ToString());
+ thisNode.AddAttribute("skipped", SkipCount.ToString());
+ }
+
+ thisNode.AddAttribute("asserts", AssertCount.ToString());
+
+ switch (ResultState.Status)
+ {
+ case TestStatus.Failed:
+ AddFailureElement(thisNode);
+ break;
+ case TestStatus.Skipped:
+ case TestStatus.Passed:
+ case TestStatus.Inconclusive:
+ if (Message != null)
+ AddReasonElement(thisNode);
+ break;
+ }
+
+ if (Output.Length > 0)
+ AddOutputElement(thisNode);
+
+
+ if (recursive && HasChildren)
+ foreach (TestResult child in Children)
+ child.AddToXml(thisNode, recursive);
+
+ return thisNode;
+ }
+
+ #endregion
+
+ #region Other Public Methods
+
+ /// <summary>
+ /// Set the result of the test
+ /// </summary>
+ /// <param name="resultState">The ResultState to use in the result</param>
+ public void SetResult(ResultState resultState)
+ {
+ SetResult(resultState, null, null);
+ }
+
+ /// <summary>
+ /// Set the result of the test
+ /// </summary>
+ /// <param name="resultState">The ResultState to use in the result</param>
+ /// <param name="message">A message associated with the result state</param>
+ public void SetResult(ResultState resultState, string message)
+ {
+ SetResult(resultState, message, null);
+ }
+
+ /// <summary>
+ /// Set the result of the test
+ /// </summary>
+ /// <param name="resultState">The ResultState to use in the result</param>
+ /// <param name="message">A message associated with the result state</param>
+ /// <param name="stackTrace">Stack trace giving the location of the command</param>
+ public void SetResult(ResultState resultState, string message, string stackTrace)
+ {
+#if PARALLEL
+ RwLock.EnterWriteLock();
+#endif
+ try
+ {
+ ResultState = resultState;
+ Message = message;
+ StackTrace = stackTrace;
+ }
+ finally
+ {
+#if PARALLEL
+ RwLock.ExitWriteLock();
+#endif
+ }
+
+ // Set pseudo-counts for a test case
+ //if (IsTestCase(test))
+ //{
+ // passCount = 0;
+ // failCount = 0;
+ // skipCount = 0;
+ // inconclusiveCount = 0;
+
+ // switch (ResultState.Status)
+ // {
+ // case TestStatus.Passed:
+ // passCount++;
+ // break;
+ // case TestStatus.Failed:
+ // failCount++;
+ // break;
+ // case TestStatus.Skipped:
+ // skipCount++;
+ // break;
+ // default:
+ // case TestStatus.Inconclusive:
+ // inconclusiveCount++;
+ // break;
+ // }
+ //}
+ }
+
+ /// <summary>
+ /// Set the test result based on the type of exception thrown
+ /// </summary>
+ /// <param name="ex">The exception that was thrown</param>
+ public void RecordException(Exception ex)
+ {
+ if (ex is NUnitException)
+ ex = ex.InnerException;
+
+ if (ex is ResultStateException)
+ SetResult(((ResultStateException)ex).ResultState,
+ ex.Message,
+ StackFilter.Filter(ex.StackTrace));
+#if !PORTABLE
+ else if (ex is System.Threading.ThreadAbortException)
+ SetResult(ResultState.Cancelled,
+ "Test cancelled by user",
+ ex.StackTrace);
+#endif
+ else
+ SetResult(ResultState.Error,
+ ExceptionHelper.BuildMessage(ex),
+ ExceptionHelper.BuildStackTrace(ex));
+ }
+
+ /// <summary>
+ /// Set the test result based on the type of exception thrown
+ /// </summary>
+ /// <param name="ex">The exception that was thrown</param>
+ /// <param name="site">THe FailureSite to use in the result</param>
+ public void RecordException(Exception ex, FailureSite site)
+ {
+ if (ex is NUnitException)
+ ex = ex.InnerException;
+
+ if (ex is ResultStateException)
+ SetResult(((ResultStateException)ex).ResultState.WithSite(site),
+ ex.Message,
+ StackFilter.Filter(ex.StackTrace));
+#if !PORTABLE
+ else if (ex is System.Threading.ThreadAbortException)
+ SetResult(ResultState.Cancelled.WithSite(site),
+ "Test cancelled by user",
+ ex.StackTrace);
+#endif
+ else
+ SetResult(ResultState.Error.WithSite(site),
+ ExceptionHelper.BuildMessage(ex),
+ ExceptionHelper.BuildStackTrace(ex));
+ }
+
+ /// <summary>
+ /// RecordTearDownException appends the message and stacktrace
+ /// from an exception arising during teardown of the test
+ /// to any previously recorded information, so that any
+ /// earlier failure information is not lost. Note that
+ /// calling Assert.Ignore, Assert.Inconclusive, etc. during
+ /// teardown is treated as an error. If the current result
+ /// represents a suite, it may show a teardown error even
+ /// though all contained tests passed.
+ /// </summary>
+ /// <param name="ex">The Exception to be recorded</param>
+ public void RecordTearDownException(Exception ex)
+ {
+ if (ex is NUnitException)
+ ex = ex.InnerException;
+
+ ResultState resultState = ResultState == ResultState.Cancelled
+ ? ResultState.Cancelled
+ : ResultState.Error;
+ if (Test.IsSuite)
+ resultState = resultState.WithSite(FailureSite.TearDown);
+
+ string message = "TearDown : " + ExceptionHelper.BuildMessage(ex);
+ if (Message != null)
+ message = Message + NUnit.Env.NewLine + message;
+
+ string stackTrace = "--TearDown" + NUnit.Env.NewLine + ExceptionHelper.BuildStackTrace(ex);
+ if (StackTrace != null)
+ stackTrace = StackTrace + NUnit.Env.NewLine + stackTrace;
+
+ SetResult(resultState, message, stackTrace);
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ /// <summary>
+ /// Adds a reason element to a node and returns it.
+ /// </summary>
+ /// <param name="targetNode">The target node.</param>
+ /// <returns>The new reason element.</returns>
+ private TNode AddReasonElement(TNode targetNode)
+ {
+ TNode reasonNode = targetNode.AddElement("reason");
+ return reasonNode.AddElementWithCDATA("message", Message);
+ }
+
+ /// <summary>
+ /// Adds a failure element to a node and returns it.
+ /// </summary>
+ /// <param name="targetNode">The target node.</param>
+ /// <returns>The new failure element.</returns>
+ private TNode AddFailureElement(TNode targetNode)
+ {
+ TNode failureNode = targetNode.AddElement("failure");
+
+ if (Message != null)
+ failureNode.AddElementWithCDATA("message", Message);
+
+ if (StackTrace != null)
+ failureNode.AddElementWithCDATA("stack-trace", StackTrace);
+
+ return failureNode;
+ }
+
+ private TNode AddOutputElement(TNode targetNode)
+ {
+ return targetNode.AddElementWithCDATA("output", Output);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+#if PARALLEL
+using System.Collections.Concurrent;
+#endif
+using NUnit.Framework.Interfaces;
+using System.Threading;
+#if NETCF || NET_2_0
+using NUnit.Compatibility;
+#endif
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// Represents the result of running a test suite
+ /// </summary>
+ public class TestSuiteResult : TestResult
+ {
+ private int _passCount = 0;
+ private int _failCount = 0;
+ private int _skipCount = 0;
+ private int _inconclusiveCount = 0;
+#if PARALLEL
+ private ConcurrentQueue<ITestResult> _children;
+#else
+ private List<ITestResult> _children;
+#endif
+
+ /// <summary>
+ /// Construct a TestSuiteResult base on a TestSuite
+ /// </summary>
+ /// <param name="suite">The TestSuite to which the result applies</param>
+ public TestSuiteResult(TestSuite suite) : base(suite)
+ {
+#if PARALLEL
+ _children = new ConcurrentQueue<ITestResult>();
+#else
+ _children = new List<ITestResult>();
+#endif
+ }
+
+#region Overrides
+
+ /// <summary>
+ /// Gets the number of test cases that failed
+ /// when running the test and all its children.
+ /// </summary>
+ public override int FailCount
+ {
+ get
+ {
+#if PARALLEL
+ RwLock.EnterReadLock();
+#endif
+ try
+ {
+ return _failCount;
+ }
+ finally
+ {
+#if PARALLEL
+ RwLock.ExitReadLock();
+#endif
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that passed
+ /// when running the test and all its children.
+ /// </summary>
+ public override int PassCount
+ {
+ get
+ {
+#if PARALLEL
+ RwLock.EnterReadLock();
+#endif
+ try
+ {
+ return _passCount;
+ }
+ finally
+ {
+#if PARALLEL
+ RwLock.ExitReadLock();
+#endif
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that were skipped
+ /// when running the test and all its children.
+ /// </summary>
+ public override int SkipCount
+ {
+ get
+ {
+#if PARALLEL
+ RwLock.EnterReadLock();
+#endif
+ try
+ {
+ return _skipCount;
+ }
+ finally
+ {
+#if PARALLEL
+ RwLock.ExitReadLock();
+#endif
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that were inconclusive
+ /// when running the test and all its children.
+ /// </summary>
+ public override int InconclusiveCount
+ {
+ get
+ {
+#if PARALLEL
+ RwLock.EnterReadLock();
+#endif
+ try
+ {
+ return _inconclusiveCount;
+ }
+ finally
+ {
+#if PARALLEL
+ RwLock.ExitReadLock();
+#endif
+ }
+ }
+ }
+
+ /// <summary>
+ /// Indicates whether this result has any child results.
+ /// </summary>
+ public override bool HasChildren
+ {
+ get
+ {
+#if PARALLEL
+ return !_children.IsEmpty;
+#else
+ return _children.Count != 0;
+#endif
+ }
+ }
+
+ /// <summary>
+ /// Gets the collection of child results.
+ /// </summary>
+ public override IEnumerable<ITestResult> Children
+ {
+ get { return _children; }
+ }
+
+ #endregion
+
+ #region AddResult Method
+
+ /// <summary>
+ /// Adds a child result to this result, setting this result's
+ /// ResultState to Failure if the child result failed.
+ /// </summary>
+ /// <param name="result">The result to be added</param>
+ public virtual void AddResult(ITestResult result)
+ {
+#if PARALLEL
+ var childrenAsConcurrentQueue = Children as ConcurrentQueue<ITestResult>;
+ if (childrenAsConcurrentQueue != null)
+ childrenAsConcurrentQueue.Enqueue(result);
+ else
+#endif
+ {
+ var childrenAsIList = Children as IList<ITestResult>;
+ if (childrenAsIList != null)
+ childrenAsIList.Add(result);
+ else
+ throw new NotSupportedException("cannot add results to Children");
+
+ }
+
+#if PARALLEL
+ RwLock.EnterWriteLock();
+#endif
+ try
+ {
+ // If this result is marked cancelled, don't change it
+ if (ResultState != ResultState.Cancelled)
+ {
+ switch (result.ResultState.Status)
+ {
+ case TestStatus.Passed:
+
+ if (ResultState.Status == TestStatus.Inconclusive)
+ SetResult(ResultState.Success);
+
+ break;
+
+ case TestStatus.Failed:
+
+
+ if (ResultState.Status != TestStatus.Failed)
+ SetResult(ResultState.ChildFailure, CHILD_ERRORS_MESSAGE);
+
+ break;
+
+ case TestStatus.Skipped:
+
+ if (result.ResultState.Label == "Ignored")
+ if (ResultState.Status == TestStatus.Inconclusive || ResultState.Status == TestStatus.Passed)
+ SetResult(ResultState.Ignored, CHILD_IGNORE_MESSAGE);
+
+ break;
+ }
+ }
+
+ InternalAssertCount += result.AssertCount;
+ _passCount += result.PassCount;
+ _failCount += result.FailCount;
+ _skipCount += result.SkipCount;
+ _inconclusiveCount += result.InconclusiveCount;
+ }
+ finally
+ {
+#if PARALLEL
+ RwLock.ExitWriteLock();
+#endif
+ }
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007-2016 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !PORTABLE
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using Microsoft.Win32;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// Enumeration identifying a common language
+ /// runtime implementation.
+ /// </summary>
+ public enum RuntimeType
+ {
+ /// <summary>Any supported runtime framework</summary>
+ Any,
+ /// <summary>Microsoft .NET Framework</summary>
+ Net,
+ /// <summary>Microsoft .NET Compact Framework</summary>
+ NetCF,
+ /// <summary>Microsoft Shared Source CLI</summary>
+ SSCLI,
+ /// <summary>Mono</summary>
+ Mono,
+ /// <summary>Silverlight</summary>
+ Silverlight,
+ /// <summary>MonoTouch</summary>
+ MonoTouch
+ }
+
+ /// <summary>
+ /// RuntimeFramework represents a particular version
+ /// of a common language runtime implementation.
+ /// </summary>
+ [Serializable]
+ public sealed class RuntimeFramework
+ {
+ // NOTE: This version of RuntimeFramework is for use
+ // within the NUnit framework assembly. It is simpler
+ // than the version in the test engine because it does
+ // not need to know what frameworks are available,
+ // only what framework is currently running.
+#region Static and Instance Fields
+
+ /// <summary>
+ /// DefaultVersion is an empty Version, used to indicate that
+ /// NUnit should select the CLR version to use for the test.
+ /// </summary>
+ public static readonly Version DefaultVersion = new Version(0,0);
+
+ private static readonly Lazy<RuntimeFramework> currentFramework = new Lazy<RuntimeFramework>(() =>
+ {
+#if SILVERLIGHT
+ var currentFramework = new RuntimeFramework(
+ RuntimeType.Silverlight,
+ new Version(Environment.Version.Major, Environment.Version.Minor));
+#else
+ Type monoRuntimeType = Type.GetType("Mono.Runtime", false);
+ Type monoTouchType = Type.GetType("MonoTouch.UIKit.UIApplicationDelegate,monotouch");
+ bool isMonoTouch = monoTouchType != null;
+ bool isMono = monoRuntimeType != null;
+
+ RuntimeType runtime = isMonoTouch
+ ? RuntimeType.MonoTouch
+ : isMono
+ ? RuntimeType.Mono
+ : Environment.OSVersion.Platform == PlatformID.WinCE
+ ? RuntimeType.NetCF
+ : RuntimeType.Net;
+
+ int major = Environment.Version.Major;
+ int minor = Environment.Version.Minor;
+
+ if (isMono)
+ {
+ switch (major)
+ {
+ case 1:
+ minor = 0;
+ break;
+ case 2:
+ major = 3;
+ minor = 5;
+ break;
+ }
+ }
+ else /* It's windows */
+ if (major == 2)
+ {
+ using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework"))
+ {
+ if (key != null)
+ {
+ string installRoot = key.GetValue("InstallRoot") as string;
+ if (installRoot != null)
+ {
+ if (Directory.Exists(Path.Combine(installRoot, "v3.5")))
+ {
+ major = 3;
+ minor = 5;
+ }
+ else if (Directory.Exists(Path.Combine(installRoot, "v3.0")))
+ {
+ major = 3;
+ minor = 0;
+ }
+ }
+ }
+ }
+ }
+ else if (major == 4 && Type.GetType("System.Reflection.AssemblyMetadataAttribute") != null)
+ {
+ minor = 5;
+ }
+
+ var currentFramework = new RuntimeFramework( runtime, new Version (major, minor) )
+ {
+ ClrVersion = Environment.Version
+ };
+
+ if (isMono)
+ {
+ MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod(
+ "GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding);
+ if (getDisplayNameMethod != null)
+ currentFramework.DisplayName = (string)getDisplayNameMethod.Invoke(null, new object[0]);
+ }
+#endif
+ return currentFramework;
+ });
+
+#endregion
+
+#region Constructor
+
+ /// <summary>
+ /// Construct from a runtime type and version. If the version has
+ /// two parts, it is taken as a framework version. If it has three
+ /// or more, it is taken as a CLR version. In either case, the other
+ /// version is deduced based on the runtime type and provided version.
+ /// </summary>
+ /// <param name="runtime">The runtime type of the framework</param>
+ /// <param name="version">The version of the framework</param>
+ public RuntimeFramework( RuntimeType runtime, Version version)
+ {
+ Runtime = runtime;
+
+ if (version.Build < 0)
+ InitFromFrameworkVersion(version);
+ else
+ InitFromClrVersion(version);
+
+ DisplayName = GetDefaultDisplayName(runtime, version);
+ }
+
+ private void InitFromFrameworkVersion(Version version)
+ {
+ FrameworkVersion = ClrVersion = version;
+
+ if (version.Major > 0) // 0 means any version
+ switch (Runtime)
+ {
+ case RuntimeType.Net:
+ case RuntimeType.Mono:
+ case RuntimeType.Any:
+ switch (version.Major)
+ {
+ case 1:
+ switch (version.Minor)
+ {
+ case 0:
+ ClrVersion = Runtime == RuntimeType.Mono
+ ? new Version(1, 1, 4322)
+ : new Version(1, 0, 3705);
+ break;
+ case 1:
+ if (Runtime == RuntimeType.Mono)
+ FrameworkVersion = new Version(1, 0);
+ ClrVersion = new Version(1, 1, 4322);
+ break;
+ default:
+ ThrowInvalidFrameworkVersion(version);
+ break;
+ }
+ break;
+ case 2:
+ case 3:
+ ClrVersion = new Version(2, 0, 50727);
+ break;
+ case 4:
+ ClrVersion = new Version(4, 0, 30319);
+ break;
+ default:
+ ThrowInvalidFrameworkVersion(version);
+ break;
+ }
+ break;
+
+ case RuntimeType.Silverlight:
+ ClrVersion = version.Major >= 4
+ ? new Version(4, 0, 60310)
+ : new Version(2, 0, 50727);
+ break;
+
+ case RuntimeType.NetCF:
+ switch (version.Major)
+ {
+ case 3:
+ switch (version.Minor)
+ {
+ case 5:
+ ClrVersion = new Version(3, 5, 7283);
+ break;
+ }
+ break;
+ }
+ break;
+ }
+ }
+
+ private static void ThrowInvalidFrameworkVersion(Version version)
+ {
+ throw new ArgumentException("Unknown framework version " + version, "version");
+ }
+
+ private void InitFromClrVersion(Version version)
+ {
+ FrameworkVersion = new Version(version.Major, version.Minor);
+ ClrVersion = version;
+ if (Runtime == RuntimeType.Mono && version.Major == 1)
+ FrameworkVersion = new Version(1, 0);
+ }
+
+#endregion
+
+#region Properties
+ /// <summary>
+ /// Static method to return a RuntimeFramework object
+ /// for the framework that is currently in use.
+ /// </summary>
+ public static RuntimeFramework CurrentFramework
+ {
+ get
+ {
+ return currentFramework.Value;
+ }
+ }
+
+ /// <summary>
+ /// The type of this runtime framework
+ /// </summary>
+ public RuntimeType Runtime { get; private set; }
+
+ /// <summary>
+ /// The framework version for this runtime framework
+ /// </summary>
+ public Version FrameworkVersion { get; private set; }
+
+ /// <summary>
+ /// The CLR version for this runtime framework
+ /// </summary>
+ public Version ClrVersion { get; private set; }
+
+ /// <summary>
+ /// Return true if any CLR version may be used in
+ /// matching this RuntimeFramework object.
+ /// </summary>
+ public bool AllowAnyVersion
+ {
+ get { return ClrVersion == DefaultVersion; }
+ }
+
+ /// <summary>
+ /// Returns the Display name for this framework
+ /// </summary>
+ public string DisplayName { get; private set; }
+
+#endregion
+
+#region Public Methods
+
+ /// <summary>
+ /// Parses a string representing a RuntimeFramework.
+ /// The string may be just a RuntimeType name or just
+ /// a Version or a hyphenated RuntimeType-Version or
+ /// a Version prefixed by 'versionString'.
+ /// </summary>
+ /// <param name="s"></param>
+ /// <returns></returns>
+ public static RuntimeFramework Parse(string s)
+ {
+ RuntimeType runtime = RuntimeType.Any;
+ Version version = DefaultVersion;
+
+ string[] parts = s.Split('-');
+ if (parts.Length == 2)
+ {
+ runtime = (RuntimeType)Enum.Parse(typeof(RuntimeType), parts[0], true);
+ string vstring = parts[1];
+ if (vstring != "")
+ version = new Version(vstring);
+ }
+ else if (char.ToLower(s[0]) == 'v')
+ {
+ version = new Version(s.Substring(1));
+ }
+ else if (IsRuntimeTypeName(s))
+ {
+ runtime = (RuntimeType)Enum.Parse(typeof(RuntimeType), s, true);
+ }
+ else
+ {
+ version = new Version(s);
+ }
+
+ return new RuntimeFramework(runtime, version);
+ }
+
+ /// <summary>
+ /// Overridden to return the short name of the framework
+ /// </summary>
+ /// <returns></returns>
+ public override string ToString()
+ {
+ if (AllowAnyVersion)
+ {
+ return Runtime.ToString().ToLower();
+ }
+ else
+ {
+ string vstring = FrameworkVersion.ToString();
+ if (Runtime == RuntimeType.Any)
+ return "v" + vstring;
+ else
+ return Runtime.ToString().ToLower() + "-" + vstring;
+ }
+ }
+
+ /// <summary>
+ /// Returns true if the current framework matches the
+ /// one supplied as an argument. Two frameworks match
+ /// if their runtime types are the same or either one
+ /// is RuntimeType.Any and all specified version components
+ /// are equal. Negative (i.e. unspecified) version
+ /// components are ignored.
+ /// </summary>
+ /// <param name="target">The RuntimeFramework to be matched.</param>
+ /// <returns>True on match, otherwise false</returns>
+ public bool Supports(RuntimeFramework target)
+ {
+ if (Runtime != RuntimeType.Any
+ && target.Runtime != RuntimeType.Any
+ && Runtime != target.Runtime)
+ return false;
+
+ if (AllowAnyVersion || target.AllowAnyVersion)
+ return true;
+
+ if (!VersionsMatch(ClrVersion, target.ClrVersion))
+ return false;
+
+ return Runtime == RuntimeType.Silverlight
+ ? FrameworkVersion.Major == target.FrameworkVersion.Major && FrameworkVersion.Minor == target.FrameworkVersion.Minor
+ : FrameworkVersion.Major >= target.FrameworkVersion.Major && FrameworkVersion.Minor >= target.FrameworkVersion.Minor;
+ }
+
+#endregion
+
+#region Helper Methods
+
+ private static bool IsRuntimeTypeName(string name)
+ {
+ return TypeHelper.GetEnumNames( typeof(RuntimeType)).Any( item => item.ToLower() == name.ToLower() );
+ }
+
+ private static string GetDefaultDisplayName(RuntimeType runtime, Version version)
+ {
+ if (version == DefaultVersion)
+ return runtime.ToString();
+ else if (runtime == RuntimeType.Any)
+ return "v" + version;
+ else
+ return runtime + " " + version;
+ }
+
+ private static bool VersionsMatch(Version v1, Version v2)
+ {
+ return v1.Major == v2.Major &&
+ v1.Minor == v2.Minor &&
+ (v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) &&
+ (v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision);
+ }
+
+#endregion
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.IO;
+using System.Text.RegularExpressions;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// StackFilter class is used to remove internal NUnit
+ /// entries from a stack trace so that the resulting
+ /// trace provides better information about the test.
+ /// </summary>
+ public static class StackFilter
+ {
+ private static readonly Regex assertOrAssumeRegex = new Regex(
+ @" NUnit\.Framework\.Ass(ert|ume)\.");
+
+ /// <summary>
+ /// Filters a raw stack trace and returns the result.
+ /// </summary>
+ /// <param name="rawTrace">The original stack trace</param>
+ /// <returns>A filtered stack trace</returns>
+ public static string Filter(string rawTrace)
+ {
+ if (rawTrace == null) return null;
+
+ StringReader sr = new StringReader(rawTrace);
+ StringWriter sw = new StringWriter();
+
+ try
+ {
+ string line;
+ // Skip past any Assert or Assume lines
+ while ((line = sr.ReadLine()) != null && assertOrAssumeRegex.IsMatch(line))
+ /*Skip*/
+ ;
+
+ // Copy lines down to the line that invoked the failing method.
+ // This is actually only needed for the compact framework, but
+ // we do it on all platforms for simplicity. Desktop platforms
+ // won't have any System.Reflection lines.
+ while (line != null && line.IndexOf(" System.Reflection.") < 0)
+ {
+ sw.WriteLine(line.Trim());
+ line = sr.ReadLine();
+ }
+ }
+ catch (Exception)
+ {
+ return rawTrace;
+ }
+ String ret = sw.ToString();
+
+ sw.Dispose();
+ sr.Dispose();
+
+ return ret;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Globalization;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// Provides methods to support legacy string comparison methods.
+ /// </summary>
+ public class StringUtil
+ {
+ /// <summary>
+ /// Compares two strings for equality, ignoring case if requested.
+ /// </summary>
+ /// <param name="strA">The first string.</param>
+ /// <param name="strB">The second string..</param>
+ /// <param name="ignoreCase">if set to <c>true</c>, the case of the letters in the strings is ignored.</param>
+ /// <returns>Zero if the strings are equivalent, a negative number if strA is sorted first, a positive number if
+ /// strB is sorted first</returns>
+ public static int Compare(string strA, string strB, bool ignoreCase)
+ {
+#if NETCF
+ return string.Compare(strA, strB, ignoreCase);
+#else
+ var comparison = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
+ return string.Compare(strA, strB, comparison);
+#endif
+ }
+
+ /// <summary>
+ /// Compares two strings for equality, ignoring case if requested.
+ /// </summary>
+ /// <param name="strA">The first string.</param>
+ /// <param name="strB">The second string..</param>
+ /// <param name="ignoreCase">if set to <c>true</c>, the case of the letters in the strings is ignored.</param>
+ /// <returns>True if the strings are equivalent, false if not.</returns>
+ public static bool StringsEqual(string strA, string strB, bool ignoreCase)
+ {
+ return Compare(strA, strB, ignoreCase) == 0;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// The TestCaseParameters class encapsulates method arguments and
+ /// other selected parameters needed for constructing
+ /// a parameterized test case.
+ /// </summary>
+ public class TestCaseParameters : TestParameters, ITestCaseData, IApplyToTest
+ {
+ #region Instance Fields
+
+ /// <summary>
+ /// The expected result to be returned
+ /// </summary>
+ private object _expectedResult;
+
+ #endregion
+
+ #region Constructors
+
+ /// <summary>
+ /// Default Constructor creates an empty parameter set
+ /// </summary>
+ public TestCaseParameters() { }
+
+ /// <summary>
+ /// Construct a non-runnable ParameterSet, specifying
+ /// the provider exception that made it invalid.
+ /// </summary>
+ public TestCaseParameters(Exception exception) : base(exception) { }
+
+ /// <summary>
+ /// Construct a parameter set with a list of arguments
+ /// </summary>
+ /// <param name="args"></param>
+ public TestCaseParameters(object[] args) : base(args) { }
+
+ /// <summary>
+ /// Construct a ParameterSet from an object implementing ITestCaseData
+ /// </summary>
+ /// <param name="data"></param>
+ public TestCaseParameters(ITestCaseData data) : base(data)
+ {
+ if (data.HasExpectedResult)
+ ExpectedResult = data.ExpectedResult;
+ }
+
+ #endregion
+
+ #region ITestCaseData Members
+
+ /// <summary>
+ /// The expected result of the test, which
+ /// must match the method return type.
+ /// </summary>
+ public object ExpectedResult
+ {
+ get { return _expectedResult; }
+ set
+ {
+ _expectedResult = value;
+ HasExpectedResult = true;
+ }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether an expected result was specified.
+ /// </summary>
+ public bool HasExpectedResult { get; set; }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Diagnostics;
+using System.IO;
+using System.Threading;
+using NUnit.Framework.Constraints;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal.Execution;
+
+#if !SILVERLIGHT && !NETCF && !PORTABLE
+using System.Runtime.Remoting.Messaging;
+using System.Security.Principal;
+using NUnit.Compatibility;
+#endif
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// Helper class used to save and restore certain static or
+ /// singleton settings in the environment that affect tests
+ /// or which might be changed by the user tests.
+ ///
+ /// An internal class is used to hold settings and a stack
+ /// of these objects is pushed and popped as Save and Restore
+ /// are called.
+ /// </summary>
+ public class TestExecutionContext
+#if !SILVERLIGHT && !NETCF && !PORTABLE
+ : LongLivedMarshalByRefObject, ILogicalThreadAffinative
+#endif
+ {
+ // NOTE: Be very careful when modifying this class. It uses
+ // conditional compilation extensively and you must give
+ // thought to whether any new features will be supported
+ // on each platform. In particular, instance fields,
+ // properties, initialization and restoration must all
+ // use the same conditions for each feature.
+
+ #region Instance Fields
+
+ /// <summary>
+ /// Link to a prior saved context
+ /// </summary>
+ private TestExecutionContext _priorContext;
+
+ /// <summary>
+ /// Indicates that a stop has been requested
+ /// </summary>
+ private TestExecutionStatus _executionStatus;
+
+ /// <summary>
+ /// The event listener currently receiving notifications
+ /// </summary>
+ private ITestListener _listener = TestListener.NULL;
+
+ /// <summary>
+ /// The number of assertions for the current test
+ /// </summary>
+ private int _assertCount;
+
+ private Randomizer _randomGenerator;
+
+ /// <summary>
+ /// The current culture
+ /// </summary>
+ private CultureInfo _currentCulture;
+
+ /// <summary>
+ /// The current UI culture
+ /// </summary>
+ private CultureInfo _currentUICulture;
+
+ /// <summary>
+ /// The current test result
+ /// </summary>
+ private TestResult _currentResult;
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// The current Principal.
+ /// </summary>
+ private IPrincipal _currentPrincipal;
+#endif
+
+ #endregion
+
+ #region Constructors
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestExecutionContext"/> class.
+ /// </summary>
+ public TestExecutionContext()
+ {
+ _priorContext = null;
+ TestCaseTimeout = 0;
+ UpstreamActions = new List<ITestAction>();
+
+ _currentCulture = CultureInfo.CurrentCulture;
+ _currentUICulture = CultureInfo.CurrentUICulture;
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ _currentPrincipal = Thread.CurrentPrincipal;
+#endif
+
+ CurrentValueFormatter = (val) => MsgUtils.DefaultValueFormatter(val);
+ IsSingleThreaded = false;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestExecutionContext"/> class.
+ /// </summary>
+ /// <param name="other">An existing instance of TestExecutionContext.</param>
+ public TestExecutionContext(TestExecutionContext other)
+ {
+ _priorContext = other;
+
+ CurrentTest = other.CurrentTest;
+ CurrentResult = other.CurrentResult;
+ TestObject = other.TestObject;
+ WorkDirectory = other.WorkDirectory;
+ _listener = other._listener;
+ StopOnError = other.StopOnError;
+ TestCaseTimeout = other.TestCaseTimeout;
+ UpstreamActions = new List<ITestAction>(other.UpstreamActions);
+
+ _currentCulture = other.CurrentCulture;
+ _currentUICulture = other.CurrentUICulture;
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ _currentPrincipal = other.CurrentPrincipal;
+#endif
+
+ CurrentValueFormatter = other.CurrentValueFormatter;
+
+ Dispatcher = other.Dispatcher;
+ ParallelScope = other.ParallelScope;
+ IsSingleThreaded = other.IsSingleThreaded;
+ }
+
+ #endregion
+
+ #region Static Singleton Instance
+
+ // NOTE: We use different implementations for various platforms
+
+ // If a user creates a thread then the current context
+ // will be null. This also happens when the compiler
+ // automatically creates threads for async methods.
+ // We create a new context, which is automatically
+ // populated with values taken from the current thread.
+
+#if SILVERLIGHT || PORTABLE
+ // In the Silverlight and portable builds, we use a ThreadStatic
+ // field to hold the current TestExecutionContext.
+
+ [ThreadStatic]
+ private static TestExecutionContext _currentContext;
+
+ /// <summary>
+ /// Gets and sets the current context.
+ /// </summary>
+ public static TestExecutionContext CurrentContext
+ {
+ get
+ {
+ if (_currentContext == null)
+ _currentContext = new TestExecutionContext();
+
+ return _currentContext;
+ }
+ private set
+ {
+ _currentContext = value;
+ }
+ }
+#elif NETCF
+ // In the compact framework build, we use a LocalStoreDataSlot
+
+ private static LocalDataStoreSlot contextSlot = Thread.AllocateDataSlot();
+
+ /// <summary>
+ /// Gets and sets the current context.
+ /// </summary>
+ public static TestExecutionContext CurrentContext
+ {
+ get
+ {
+ var current = GetTestExecutionContext();
+ if (current == null)
+ {
+ current = new TestExecutionContext();
+ Thread.SetData(contextSlot, current);
+ }
+
+ return current;
+ }
+ private set
+ {
+ Thread.SetData(contextSlot, value);
+ }
+ }
+
+ /// <summary>
+ /// Get the current context or return null if none is found.
+ /// </summary>
+ public static TestExecutionContext GetTestExecutionContext()
+ {
+ return (TestExecutionContext)Thread.GetData(contextSlot);
+ }
+#else
+ // In all other builds, we use the CallContext
+
+ private static readonly string CONTEXT_KEY = "NUnit.Framework.TestContext";
+
+ /// <summary>
+ /// Gets and sets the current context.
+ /// </summary>
+ public static TestExecutionContext CurrentContext
+ {
+ get
+ {
+ var context = GetTestExecutionContext();
+ if (context == null) // This can happen on Mono
+ {
+ context = new TestExecutionContext();
+ CallContext.SetData(CONTEXT_KEY, context);
+ }
+
+ return context;
+ }
+ private set
+ {
+ if (value == null)
+ CallContext.FreeNamedDataSlot(CONTEXT_KEY);
+ else
+ CallContext.SetData(CONTEXT_KEY, value);
+ }
+ }
+
+ /// <summary>
+ /// Get the current context or return null if none is found.
+ /// </summary>
+ public static TestExecutionContext GetTestExecutionContext()
+ {
+ return CallContext.GetData(CONTEXT_KEY) as TestExecutionContext;
+ }
+#endif
+
+ /// <summary>
+ /// Clear the current context. This is provided to
+ /// prevent "leakage" of the CallContext containing
+ /// the current context back to any runners.
+ /// </summary>
+ public static void ClearCurrentContext()
+ {
+ CurrentContext = null;
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Gets or sets the current test
+ /// </summary>
+ public Test CurrentTest { get; set; }
+
+ /// <summary>
+ /// The time the current test started execution
+ /// </summary>
+ public DateTime StartTime { get; set; }
+
+ /// <summary>
+ /// The time the current test started in Ticks
+ /// </summary>
+ public long StartTicks { get; set; }
+
+ /// <summary>
+ /// Gets or sets the current test result
+ /// </summary>
+ public TestResult CurrentResult
+ {
+ get { return _currentResult; }
+ set
+ {
+ _currentResult = value;
+ if (value != null)
+ OutWriter = value.OutWriter;
+ }
+ }
+
+ /// <summary>
+ /// Gets a TextWriter that will send output to the current test result.
+ /// </summary>
+ public TextWriter OutWriter { get; private set; }
+
+ /// <summary>
+ /// The current test object - that is the user fixture
+ /// object on which tests are being executed.
+ /// </summary>
+ public object TestObject { get; set; }
+
+ /// <summary>
+ /// Get or set the working directory
+ /// </summary>
+ public string WorkDirectory { get; set; }
+
+ /// <summary>
+ /// Get or set indicator that run should stop on the first error
+ /// </summary>
+ public bool StopOnError { get; set; }
+
+ /// <summary>
+ /// Gets an enum indicating whether a stop has been requested.
+ /// </summary>
+ public TestExecutionStatus ExecutionStatus
+ {
+ get
+ {
+ // ExecutionStatus may have been set to StopRequested or AbortRequested
+ // in a prior context. If so, reflect the same setting in this context.
+ if (_executionStatus == TestExecutionStatus.Running && _priorContext != null)
+ _executionStatus = _priorContext.ExecutionStatus;
+
+ return _executionStatus;
+ }
+ set
+ {
+ _executionStatus = value;
+
+ // Push the same setting up to all prior contexts
+ if (_priorContext != null)
+ _priorContext.ExecutionStatus = value;
+ }
+ }
+
+ /// <summary>
+ /// The current test event listener
+ /// </summary>
+ internal ITestListener Listener
+ {
+ get { return _listener; }
+ set { _listener = value; }
+ }
+
+ /// <summary>
+ /// The current WorkItemDispatcher. Made public for
+ /// use by nunitlite.tests
+ /// </summary>
+ public IWorkItemDispatcher Dispatcher { get; set; }
+
+ /// <summary>
+ /// The ParallelScope to be used by tests running in this context.
+ /// For builds with out the parallel feature, it has no effect.
+ /// </summary>
+ public ParallelScope ParallelScope { get; set; }
+
+ /// <summary>
+ /// The unique name of the worker that spawned the context.
+ /// For builds with out the parallel feature, it is null.
+ /// </summary>
+ public string WorkerId {get; internal set;}
+
+ /// <summary>
+ /// Gets the RandomGenerator specific to this Test
+ /// </summary>
+ public Randomizer RandomGenerator
+ {
+ get
+ {
+ if (_randomGenerator == null)
+ _randomGenerator = new Randomizer(CurrentTest.Seed);
+ return _randomGenerator;
+ }
+ }
+
+ /// <summary>
+ /// Gets the assert count.
+ /// </summary>
+ /// <value>The assert count.</value>
+ internal int AssertCount
+ {
+ get { return _assertCount; }
+ }
+
+ /// <summary>
+ /// Gets or sets the test case timeout value
+ /// </summary>
+ public int TestCaseTimeout { get; set; }
+
+ /// <summary>
+ /// Gets a list of ITestActions set by upstream tests
+ /// </summary>
+ public List<ITestAction> UpstreamActions { get; private set; }
+
+ // TODO: Put in checks on all of these settings
+ // with side effects so we only change them
+ // if the value is different
+
+ /// <summary>
+ /// Saves or restores the CurrentCulture
+ /// </summary>
+ public CultureInfo CurrentCulture
+ {
+ get { return _currentCulture; }
+ set
+ {
+ _currentCulture = value;
+#if !NETCF && !PORTABLE
+ Thread.CurrentThread.CurrentCulture = _currentCulture;
+#endif
+ }
+ }
+
+ /// <summary>
+ /// Saves or restores the CurrentUICulture
+ /// </summary>
+ public CultureInfo CurrentUICulture
+ {
+ get { return _currentUICulture; }
+ set
+ {
+ _currentUICulture = value;
+#if !NETCF && !PORTABLE
+ Thread.CurrentThread.CurrentUICulture = _currentUICulture;
+#endif
+ }
+ }
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Gets or sets the current <see cref="IPrincipal"/> for the Thread.
+ /// </summary>
+ public IPrincipal CurrentPrincipal
+ {
+ get { return _currentPrincipal; }
+ set
+ {
+ _currentPrincipal = value;
+ Thread.CurrentPrincipal = _currentPrincipal;
+ }
+ }
+#endif
+
+ /// <summary>
+ /// The current head of the ValueFormatter chain, copied from MsgUtils.ValueFormatter
+ /// </summary>
+ public ValueFormatter CurrentValueFormatter { get; private set; }
+
+ /// <summary>
+ /// If true, all tests must run on the same thread. No new thread may be spawned.
+ /// </summary>
+ public bool IsSingleThreaded { get; set; }
+
+ #endregion
+
+ #region Instance Methods
+
+ /// <summary>
+ /// Record any changes in the environment made by
+ /// the test code in the execution context so it
+ /// will be passed on to lower level tests.
+ /// </summary>
+ public void UpdateContextFromEnvironment()
+ {
+ _currentCulture = CultureInfo.CurrentCulture;
+ _currentUICulture = CultureInfo.CurrentUICulture;
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ _currentPrincipal = Thread.CurrentPrincipal;
+#endif
+ }
+
+ /// <summary>
+ /// Set up the execution environment to match a context.
+ /// Note that we may be running on the same thread where the
+ /// context was initially created or on a different thread.
+ /// </summary>
+ public void EstablishExecutionEnvironment()
+ {
+#if !NETCF && !PORTABLE
+ Thread.CurrentThread.CurrentCulture = _currentCulture;
+ Thread.CurrentThread.CurrentUICulture = _currentUICulture;
+#endif
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ Thread.CurrentPrincipal = _currentPrincipal;
+#endif
+
+ CurrentContext = this;
+ }
+
+ /// <summary>
+ /// Increments the assert count by one.
+ /// </summary>
+ public void IncrementAssertCount()
+ {
+ Interlocked.Increment(ref _assertCount);
+ }
+
+ /// <summary>
+ /// Increments the assert count by a specified amount.
+ /// </summary>
+ public void IncrementAssertCount(int count)
+ {
+ // TODO: Temporary implementation
+ while (count-- > 0)
+ Interlocked.Increment(ref _assertCount);
+ }
+
+ /// <summary>
+ /// Adds a new ValueFormatterFactory to the chain of formatters
+ /// </summary>
+ /// <param name="formatterFactory">The new factory</param>
+ public void AddFormatter(ValueFormatterFactory formatterFactory)
+ {
+ CurrentValueFormatter = formatterFactory(CurrentValueFormatter);
+ }
+
+ #endregion
+
+ #region InitializeLifetimeService
+
+#if !SILVERLIGHT && !NETCF && !PORTABLE
+ /// <summary>
+ /// Obtain lifetime service object
+ /// </summary>
+ /// <returns></returns>
+ public override object InitializeLifetimeService()
+ {
+ return null;
+ }
+#endif
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// Enumeration indicating whether the tests are
+ /// running normally or being cancelled.
+ /// </summary>
+ public enum TestExecutionStatus
+ {
+ /// <summary>
+ /// Running normally with no stop requested
+ /// </summary>
+ Running,
+
+ /// <summary>
+ /// A graceful stop has been requested
+ /// </summary>
+ StopRequested,
+
+ /// <summary>
+ /// A forced stop has been requested
+ /// </summary>
+ AbortRequested
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Xml;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal.Filters;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// Interface to be implemented by filters applied to tests.
+ /// The filter applies when running the test, after it has been
+ /// loaded, since this is the only time an ITest exists.
+ /// </summary>
+ //[Serializable]
+ public abstract class TestFilter : ITestFilter
+ {
+ /// <summary>
+ /// Unique Empty filter.
+ /// </summary>
+ public readonly static TestFilter Empty = new EmptyFilter();
+
+ /// <summary>
+ /// Indicates whether this is the EmptyFilter
+ /// </summary>
+ public bool IsEmpty
+ {
+ get { return this is TestFilter.EmptyFilter; }
+ }
+
+ /// <summary>
+ /// Indicates whether this is a top-level filter,
+ /// not contained in any other filter.
+ /// </summary>
+ public bool TopLevel { get; set; }
+
+ /// <summary>
+ /// Determine if a particular test passes the filter criteria. The default
+ /// implementation checks the test itself, its parents and any descendants.
+ ///
+ /// Derived classes may override this method or any of the Match methods
+ /// to change the behavior of the filter.
+ /// </summary>
+ /// <param name="test">The test to which the filter is applied</param>
+ /// <returns>True if the test passes the filter, otherwise false</returns>
+ public virtual bool Pass(ITest test)
+ {
+ return Match(test) || MatchParent(test) || MatchDescendant(test);
+ }
+
+ /// <summary>
+ /// Determine if a test matches the filter expicitly. That is, it must
+ /// be a direct match of the test itself or one of it's children.
+ /// </summary>
+ /// <param name="test">The test to which the filter is applied</param>
+ /// <returns>True if the test matches the filter explicityly, otherwise false</returns>
+ public virtual bool IsExplicitMatch(ITest test)
+ {
+ return Match(test) || MatchDescendant(test);
+ }
+
+ /// <summary>
+ /// Determine whether the test itself matches the filter criteria, without
+ /// examining either parents or descendants. This is overridden by each
+ /// different type of filter to perform the necessary tests.
+ /// </summary>
+ /// <param name="test">The test to which the filter is applied</param>
+ /// <returns>True if the filter matches the any parent of the test</returns>
+ public abstract bool Match(ITest test);
+
+ /// <summary>
+ /// Determine whether any ancestor of the test matches the filter criteria
+ /// </summary>
+ /// <param name="test">The test to which the filter is applied</param>
+ /// <returns>True if the filter matches the an ancestor of the test</returns>
+ public bool MatchParent(ITest test)
+ {
+ return test.Parent != null && (Match(test.Parent) || MatchParent(test.Parent));
+ }
+
+ /// <summary>
+ /// Determine whether any descendant of the test matches the filter criteria.
+ /// </summary>
+ /// <param name="test">The test to be matched</param>
+ /// <returns>True if at least one descendant matches the filter criteria</returns>
+ protected virtual bool MatchDescendant(ITest test)
+ {
+ if (test.Tests == null)
+ return false;
+
+ foreach (ITest child in test.Tests)
+ {
+ if (Match(child) || MatchDescendant(child))
+ return true;
+ }
+
+ return false;
+ }
+
+ private static readonly char[] COMMA = new char[] { ',' };
+
+ /// <summary>
+ /// Create a TestFilter instance from an xml representation.
+ /// </summary>
+ public static TestFilter FromXml(string xmlText)
+ {
+ TNode topNode = TNode.FromXml(xmlText);
+
+ if (topNode.Name != "filter")
+ throw new Exception("Expected filter element at top level");
+
+ int count = topNode.ChildNodes.Count;
+
+ TestFilter filter = count == 0
+ ? TestFilter.Empty
+ : count == 1
+ ? FromXml(topNode.FirstChild)
+ : FromXml(topNode);
+
+ filter.TopLevel = true;
+
+ return filter;
+ }
+
+ /// <summary>
+ /// Create a TestFilter from it's TNode representation
+ /// </summary>
+ public static TestFilter FromXml(TNode node)
+ {
+ bool isRegex = node.Attributes["re"] == "1";
+
+ switch (node.Name)
+ {
+ case "filter":
+ case "and":
+ var andFilter = new AndFilter();
+ foreach (var childNode in node.ChildNodes)
+ andFilter.Add(FromXml(childNode));
+ return andFilter;
+
+ case "or":
+ var orFilter = new OrFilter();
+ foreach (var childNode in node.ChildNodes)
+ orFilter.Add(FromXml(childNode));
+ return orFilter;
+
+ case "not":
+ return new NotFilter(FromXml(node.FirstChild));
+
+ case "id":
+ return new IdFilter(node.Value);
+
+ case "test":
+ return new FullNameFilter(node.Value) { IsRegex = isRegex };
+
+ case "name":
+ return new TestNameFilter(node.Value) { IsRegex = isRegex };
+
+ case "method":
+ return new MethodNameFilter(node.Value) { IsRegex = isRegex };
+
+ case "class":
+ return new ClassNameFilter(node.Value) { IsRegex = isRegex };
+
+ case "cat":
+ return new CategoryFilter(node.Value) { IsRegex = isRegex };
+
+ case "prop":
+ string name = node.Attributes["name"];
+ if (name != null)
+ return new PropertyFilter(name, node.Value) { IsRegex = isRegex };
+ break;
+ }
+
+ throw new ArgumentException("Invalid filter element: " + node.Name, "xmlNode");
+ }
+
+ /// <summary>
+ /// Nested class provides an empty filter - one that always
+ /// returns true when called. It never matches explicitly.
+ /// </summary>
+ //[Serializable]
+ private class EmptyFilter : TestFilter
+ {
+ public override bool Match( ITest test )
+ {
+ return true;
+ }
+
+ public override bool Pass( ITest test )
+ {
+ return true;
+ }
+
+ public override bool IsExplicitMatch( ITest test )
+ {
+ return false;
+ }
+
+ public override TNode AddToXml(TNode parentNode, bool recursive)
+ {
+ return parentNode.AddElement("filter");
+ }
+ }
+
+ #region IXmlNodeBuilder Implementation
+
+ /// <summary>
+ /// Adds an XML node
+ /// </summary>
+ /// <param name="recursive">True if recursive</param>
+ /// <returns>The added XML node</returns>
+ public TNode ToXml(bool recursive)
+ {
+ return AddToXml(new TNode("dummy"), recursive);
+ }
+
+ /// <summary>
+ /// Adds an XML node
+ /// </summary>
+ /// <param name="parentNode">Parent node</param>
+ /// <param name="recursive">True if recursive</param>
+ /// <returns>The added XML node</returns>
+ public abstract TNode AddToXml(TNode parentNode, bool recursive);
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// The TestCaseParameters class encapsulates method arguments and
+ /// other selected parameters needed for constructing
+ /// a parameterized test case.
+ /// </summary>
+ public class TestFixtureParameters : TestParameters, ITestFixtureData
+ {
+ #region Constructors
+
+ /// <summary>
+ /// Default Constructor creates an empty parameter set
+ /// </summary>
+ public TestFixtureParameters() { }
+
+ /// <summary>
+ /// Construct a non-runnable ParameterSet, specifying
+ /// the provider exception that made it invalid.
+ /// </summary>
+ public TestFixtureParameters(Exception exception) : base(exception) { }
+
+ /// <summary>
+ /// Construct a parameter set with a list of arguments
+ /// </summary>
+ /// <param name="args"></param>
+ public TestFixtureParameters(params object[] args) : base(args) { }
+
+ /// <summary>
+ /// Construct a ParameterSet from an object implementing ITestCaseData
+ /// </summary>
+ /// <param name="data"></param>
+ public TestFixtureParameters(ITestFixtureData data) : base(data)
+ {
+ TypeArgs = data.TypeArgs;
+ }
+
+ #endregion
+
+ #region ITestFixtureData Members
+
+ /// <summary>
+ /// Type arguments used to create a generic fixture instance
+ /// </summary>
+ public Type[] TypeArgs { get; internal set; }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// TestListener provides an implementation of ITestListener that
+ /// does nothing. It is used only through its NULL property.
+ /// </summary>
+ public class TestListener : ITestListener
+ {
+ /// <summary>
+ /// Called when a test has just started
+ /// </summary>
+ /// <param name="test">The test that is starting</param>
+ public void TestStarted(ITest test){}
+
+ /// <summary>
+ /// Called when a test case has finished
+ /// </summary>
+ /// <param name="result">The result of the test</param>
+ public void TestFinished(ITestResult result){}
+
+ /// <summary>
+ /// Called when a test produces output for immediate display
+ /// </summary>
+ /// <param name="output">A TestOutput object containing the text to display</param>
+ public void TestOutput(TestOutput output) { }
+
+ /// <summary>
+ /// Construct a new TestListener - private so it may not be used.
+ /// </summary>
+ private TestListener() { }
+
+ /// <summary>
+ /// Get a listener that does nothing
+ /// </summary>
+ public static ITestListener NULL
+ {
+ get { return new TestListener();}
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Text;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// TestNameGenerator is able to create test names according to
+ /// a coded pattern.
+ /// </summary>
+ public class TestNameGenerator
+ {
+ // TODO: Using a static here is not good it's the easiest
+ // way to get a temporary implementation without passing the
+ // pattern all the way down the test builder hierarchy
+
+ /// <summary>
+ /// Default pattern used to generate names
+ /// </summary>
+ public static string DefaultTestNamePattern = "{m}{a}";
+
+ // The name pattern used by this TestNameGenerator
+ private string _pattern;
+
+ // The list of NameFragments used to generate names
+ private List<NameFragment> _fragments;
+
+ /// <summary>
+ /// Construct a TestNameGenerator
+ /// </summary>
+ public TestNameGenerator()
+ {
+ _pattern = DefaultTestNamePattern;
+ }
+
+ /// <summary>
+ /// Construct a TestNameGenerator
+ /// </summary>
+ /// <param name="pattern">The pattern used by this generator.</param>
+ public TestNameGenerator(string pattern)
+ {
+ _pattern = pattern;
+ }
+
+ /// <summary>
+ /// Get the display name for a TestMethod and it's arguments
+ /// </summary>
+ /// <param name="testMethod">A TestMethod</param>
+ /// <returns>The display name</returns>
+ public string GetDisplayName(TestMethod testMethod)
+ {
+ return GetDisplayName(testMethod, null);
+ }
+
+ /// <summary>
+ /// Get the display name for a TestMethod and it's arguments
+ /// </summary>
+ /// <param name="testMethod">A TestMethod</param>
+ /// <param name="args">Arguments to be used</param>
+ /// <returns>The display name</returns>
+ public string GetDisplayName(TestMethod testMethod, object[] args)
+ {
+ if (_fragments == null)
+ _fragments = BuildFragmentList(_pattern);
+
+ var result = new StringBuilder();
+
+ foreach (var fragment in _fragments)
+ result.Append(fragment.GetText(testMethod, args));
+
+ return result.ToString();
+ }
+
+ #region Helper Methods
+
+ private static List<NameFragment> BuildFragmentList(string pattern)
+ {
+ var fragments = new List<NameFragment>();
+
+ // Build a list of actions so this generator can be applied to
+ // multiple types and methods.
+
+ int start = 0;
+ while (start < pattern.Length)
+ {
+ int lcurly = pattern.IndexOf('{', start);
+ if (lcurly < 0) // No more substitutions in pattern
+ break;
+
+ int rcurly = pattern.IndexOf('}', lcurly);
+ if (rcurly < 0)
+ break;
+
+ if (lcurly > start) // Handle fixedixed text before curly brace
+ fragments.Add(new FixedTextFragment(pattern.Substring(start, lcurly - start)));
+
+ string token = pattern.Substring(lcurly, rcurly - lcurly + 1);
+
+ switch (token)
+ {
+ case "{m}":
+ fragments.Add(new MethodNameFragment());
+ break;
+ case "{i}":
+ fragments.Add(new TestIDFragment());
+ break;
+ case "{n}":
+ fragments.Add(new NamespaceFragment());
+ break;
+ case "{c}":
+ fragments.Add(new ClassNameFragment());
+ break;
+ case "{C}":
+ fragments.Add(new ClassFullNameFragment());
+ break;
+ case "{M}":
+ fragments.Add(new MethodFullNameFragment());
+ break;
+ case "{a}":
+ fragments.Add(new ArgListFragment(0));
+ break;
+ case "{0}":
+ case "{1}":
+ case "{2}":
+ case "{3}":
+ case "{4}":
+ case "{5}":
+ case "{6}":
+ case "{7}":
+ case "{8}":
+ case "{9}":
+ int index = token[1] - '0';
+ fragments.Add(new ArgumentFragment(index, 40));
+ break;
+ default:
+ char c = token[1];
+ if (token.Length >= 5 && token[2] == ':' && (c == 'a' || char.IsDigit(c)))
+ {
+ int length;
+
+ // NOTE: The code would be much simpler using TryParse. However,
+ // that method doesn't exist in the Compact Framework.
+ try
+ {
+ length = int.Parse(token.Substring(3, token.Length - 4));
+ }
+ catch
+ {
+ length = -1;
+ }
+ if (length > 0)
+ {
+ if (c == 'a')
+ fragments.Add(new ArgListFragment(length));
+ else // It's a digit
+ fragments.Add(new ArgumentFragment(c - '0', length));
+ break;
+ }
+ }
+
+ // Output the erroneous token to aid user in debugging
+ fragments.Add(new FixedTextFragment(token));
+ break;
+ }
+
+ start = rcurly + 1;
+ }
+
+
+ // Output any trailing plain text
+ if (start < pattern.Length)
+ fragments.Add(new FixedTextFragment(pattern.Substring(start)));
+
+ return fragments;
+ }
+
+ #endregion
+
+ #region Nested Classes Representing Name Fragments
+
+ private abstract class NameFragment
+ {
+ private const string THREE_DOTS = "...";
+
+ public virtual string GetText(TestMethod testMethod, object[] args)
+ {
+ return GetText(testMethod.Method.MethodInfo, args);
+ }
+
+ public abstract string GetText(MethodInfo method, object[] args);
+
+ protected static void AppendGenericTypeNames(StringBuilder sb, MethodInfo method)
+ {
+ sb.Append("<");
+ int cnt = 0;
+ foreach (Type t in method.GetGenericArguments())
+ {
+ if (cnt++ > 0) sb.Append(",");
+ sb.Append(t.Name);
+ }
+ sb.Append(">");
+ }
+
+ protected static string GetDisplayString(object arg, int stringMax)
+ {
+ string display = arg == null
+ ? "null"
+ : Convert.ToString(arg, System.Globalization.CultureInfo.InvariantCulture);
+
+ if (arg is double)
+ {
+ double d = (double)arg;
+
+ if (double.IsNaN(d))
+ display = "double.NaN";
+ else if (double.IsPositiveInfinity(d))
+ display = "double.PositiveInfinity";
+ else if (double.IsNegativeInfinity(d))
+ display = "double.NegativeInfinity";
+ else if (d == double.MaxValue)
+ display = "double.MaxValue";
+ else if (d == double.MinValue)
+ display = "double.MinValue";
+ else
+ {
+ if (display.IndexOf('.') == -1)
+ display += ".0";
+ display += "d";
+ }
+ }
+ else if (arg is float)
+ {
+ float f = (float)arg;
+
+ if (float.IsNaN(f))
+ display = "float.NaN";
+ else if (float.IsPositiveInfinity(f))
+ display = "float.PositiveInfinity";
+ else if (float.IsNegativeInfinity(f))
+ display = "float.NegativeInfinity";
+ else if (f == float.MaxValue)
+ display = "float.MaxValue";
+ else if (f == float.MinValue)
+ display = "float.MinValue";
+ else
+ {
+ if (display.IndexOf('.') == -1)
+ display += ".0";
+ display += "f";
+ }
+ }
+ else if (arg is decimal)
+ {
+ decimal d = (decimal)arg;
+ if (d == decimal.MinValue)
+ display = "decimal.MinValue";
+ else if (d == decimal.MaxValue)
+ display = "decimal.MaxValue";
+ else
+ display += "m";
+ }
+ else if (arg is long)
+ {
+ if (arg.Equals(long.MinValue))
+ display = "long.MinValue";
+ else if (arg.Equals(long.MaxValue))
+ display = "long.MaxValue";
+ else
+ display += "L";
+ }
+ else if (arg is ulong)
+ {
+ ulong ul = (ulong)arg;
+ if (ul == ulong.MinValue)
+ display = "ulong.MinValue";
+ else if (ul == ulong.MaxValue)
+ display = "ulong.MaxValue";
+ else
+ display += "UL";
+ }
+ else if (arg is string)
+ {
+ var str = (string)arg;
+ bool tooLong = stringMax > 0 && str.Length > stringMax;
+ int limit = tooLong ? stringMax - THREE_DOTS.Length : 0;
+
+ StringBuilder sb = new StringBuilder();
+ sb.Append("\"");
+ foreach (char c in str)
+ {
+ sb.Append(EscapeCharInString(c));
+ if (tooLong && sb.Length > limit)
+ {
+ sb.Append(THREE_DOTS);
+ break;
+ }
+ }
+ sb.Append("\"");
+ display = sb.ToString();
+ }
+ else if (arg is char)
+ {
+ display = "\'" + EscapeSingleChar((char)arg) + "\'";
+ }
+ else if (arg is int)
+ {
+ if (arg.Equals(int.MaxValue))
+ display = "int.MaxValue";
+ else if (arg.Equals(int.MinValue))
+ display = "int.MinValue";
+ }
+ else if (arg is uint)
+ {
+ if (arg.Equals(uint.MaxValue))
+ display = "uint.MaxValue";
+ else if (arg.Equals(uint.MinValue))
+ display = "uint.MinValue";
+ }
+ else if (arg is short)
+ {
+ if (arg.Equals(short.MaxValue))
+ display = "short.MaxValue";
+ else if (arg.Equals(short.MinValue))
+ display = "short.MinValue";
+ }
+ else if (arg is ushort)
+ {
+ if (arg.Equals(ushort.MaxValue))
+ display = "ushort.MaxValue";
+ else if (arg.Equals(ushort.MinValue))
+ display = "ushort.MinValue";
+ }
+ else if (arg is byte)
+ {
+ if (arg.Equals(byte.MaxValue))
+ display = "byte.MaxValue";
+ else if (arg.Equals(byte.MinValue))
+ display = "byte.MinValue";
+ }
+ else if (arg is sbyte)
+ {
+ if (arg.Equals(sbyte.MaxValue))
+ display = "sbyte.MaxValue";
+ else if (arg.Equals(sbyte.MinValue))
+ display = "sbyte.MinValue";
+ }
+
+ return display;
+ }
+
+ private static string EscapeSingleChar(char c)
+ {
+ if (c == '\'')
+ return "\\\'";
+
+ return EscapeControlChar(c);
+ }
+
+ private static string EscapeCharInString(char c)
+ {
+ if (c == '"')
+ return "\\\"";
+
+ return EscapeControlChar(c);
+ }
+
+ private static string EscapeControlChar(char c)
+ {
+ switch (c)
+ {
+ case '\\':
+ return "\\\\";
+ case '\0':
+ return "\\0";
+ case '\a':
+ return "\\a";
+ case '\b':
+ return "\\b";
+ case '\f':
+ return "\\f";
+ case '\n':
+ return "\\n";
+ case '\r':
+ return "\\r";
+ case '\t':
+ return "\\t";
+ case '\v':
+ return "\\v";
+
+ case '\x0085':
+ case '\x2028':
+ case '\x2029':
+ return string.Format("\\x{0:X4}", (int)c);
+
+ default:
+ return c.ToString();
+ }
+ }
+ }
+
+ private class TestIDFragment : NameFragment
+ {
+ public override string GetText(MethodInfo method, object[] args)
+ {
+ return "{i}"; // No id available using MethodInfo
+ }
+
+ public override string GetText(TestMethod testMethod, object[] args)
+ {
+ return testMethod.Id;
+ }
+ }
+
+ private class FixedTextFragment : NameFragment
+ {
+ private string _text;
+
+ public FixedTextFragment(string text)
+ {
+ _text = text;
+ }
+
+ public override string GetText(MethodInfo method, object[] args)
+ {
+ return _text;
+ }
+ }
+
+ private class MethodNameFragment : NameFragment
+ {
+ public override string GetText(MethodInfo method, object[] args)
+ {
+ var sb = new StringBuilder();
+
+ sb.Append(method.Name);
+
+ if (method.IsGenericMethod)
+ AppendGenericTypeNames(sb, method);
+
+ return sb.ToString();
+ }
+ }
+
+ private class NamespaceFragment : NameFragment
+ {
+ public override string GetText(MethodInfo method, object[] args)
+ {
+ return method.DeclaringType.Namespace;
+ }
+ }
+
+ private class MethodFullNameFragment : NameFragment
+ {
+ public override string GetText(MethodInfo method, object[] args)
+ {
+ var sb = new StringBuilder();
+
+ sb.Append(method.DeclaringType.FullName);
+ sb.Append('.');
+ sb.Append(method.Name);
+
+ if (method.IsGenericMethod)
+ AppendGenericTypeNames(sb, method);
+
+ return sb.ToString();
+ }
+ }
+
+ private class ClassNameFragment : NameFragment
+ {
+ public override string GetText(MethodInfo method, object[] args)
+ {
+ return method.DeclaringType.Name;
+ }
+ }
+
+ private class ClassFullNameFragment : NameFragment
+ {
+ public override string GetText(MethodInfo method, object[] args)
+ {
+ return method.DeclaringType.FullName;
+ }
+ }
+
+ private class ArgListFragment : NameFragment
+ {
+ private int _maxStringLength;
+
+ public ArgListFragment(int maxStringLength)
+ {
+ _maxStringLength = maxStringLength;
+ }
+
+ public override string GetText(MethodInfo method, object[] arglist)
+ {
+ var sb = new StringBuilder();
+
+ if (arglist != null)
+ {
+ sb.Append('(');
+
+ for (int i = 0; i < arglist.Length; i++)
+ {
+ if (i > 0) sb.Append(",");
+ sb.Append(GetDisplayString(arglist[i], _maxStringLength));
+ }
+
+ sb.Append(')');
+ }
+
+ return sb.ToString();
+ }
+ }
+
+ private class ArgumentFragment : NameFragment
+ {
+ private int _index;
+ private int _maxStringLength;
+
+ public ArgumentFragment(int index, int maxStringLength)
+ {
+ _index = index;
+ _maxStringLength = maxStringLength;
+ }
+
+ public override string GetText(MethodInfo method, object[] args)
+ {
+ return _index < args.Length
+ ? GetDisplayString(args[_index], _maxStringLength)
+ : string.Empty;
+ }
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// TestParameters is the abstract base class for all classes
+ /// that know how to provide data for constructing a test.
+ /// </summary>
+ public abstract class TestParameters : ITestData, IApplyToTest
+ {
+ #region Constructors
+
+ /// <summary>
+ /// Default Constructor creates an empty parameter set
+ /// </summary>
+ public TestParameters()
+ {
+ RunState = RunState.Runnable;
+ Properties = new PropertyBag();
+ }
+
+ /// <summary>
+ /// Construct a parameter set with a list of arguments
+ /// </summary>
+ /// <param name="args"></param>
+ public TestParameters(object[] args)
+ {
+ RunState = RunState.Runnable;
+ InitializeAguments(args);
+ Properties = new PropertyBag();
+ }
+
+ /// <summary>
+ /// Construct a non-runnable ParameterSet, specifying
+ /// the provider exception that made it invalid.
+ /// </summary>
+ public TestParameters(Exception exception)
+ {
+ RunState = RunState.NotRunnable;
+ Properties = new PropertyBag();
+
+ Properties.Set(PropertyNames.SkipReason, ExceptionHelper.BuildMessage(exception));
+ Properties.Set(PropertyNames.ProviderStackTrace, ExceptionHelper.BuildStackTrace(exception));
+ }
+
+ /// <summary>
+ /// Construct a ParameterSet from an object implementing ITestData
+ /// </summary>
+ /// <param name="data"></param>
+ public TestParameters(ITestData data)
+ {
+ RunState = data.RunState;
+ Properties = new PropertyBag();
+
+ TestName = data.TestName;
+
+ InitializeAguments(data.Arguments);
+
+ foreach (string key in data.Properties.Keys)
+ this.Properties[key] = data.Properties[key];
+ }
+
+ private void InitializeAguments(object[] args)
+ {
+ OriginalArguments = args;
+
+ // We need to copy args, since we may change them
+ var numArgs = args.Length;
+ Arguments = new object[numArgs];
+ Array.Copy(args, Arguments, numArgs);
+ }
+
+ #endregion
+
+ #region ITestData Members
+
+ /// <summary>
+ /// The RunState for this set of parameters.
+ /// </summary>
+ public RunState RunState { get; set; }
+
+ /// <summary>
+ /// The arguments to be used in running the test,
+ /// which must match the method signature.
+ /// </summary>
+ public object[] Arguments { get; internal set; }
+
+ /// <summary>
+ /// A name to be used for this test case in lieu
+ /// of the standard generated name containing
+ /// the argument list.
+ /// </summary>
+ public string TestName { get; set; }
+
+ /// <summary>
+ /// Gets the property dictionary for this test
+ /// </summary>
+ public IPropertyBag Properties { get; private set; }
+
+ #endregion
+
+ #region IApplyToTest Members
+
+ /// <summary>
+ /// Applies ParameterSet _values to the test itself.
+ /// </summary>
+ /// <param name="test">A test.</param>
+ public void ApplyToTest(Test test)
+ {
+ if (this.RunState != RunState.Runnable)
+ test.RunState = this.RunState;
+
+ foreach (string key in Properties.Keys)
+ foreach (object value in Properties[key])
+ test.Properties.Add(key, value);
+ }
+
+ #endregion
+
+ #region Other Public Properties
+
+ /// <summary>
+ /// The original arguments provided by the user,
+ /// used for display purposes.
+ /// </summary>
+ public object[] OriginalArguments { get; private set; }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Web.UI;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// TestProgressReporter translates ITestListener events into
+ /// the async callbacks that are used to inform the client
+ /// software about the progress of a test run.
+ /// </summary>
+ public class TestProgressReporter : ITestListener
+ {
+ static Logger log = InternalTrace.GetLogger("TestProgressReporter");
+
+ private ICallbackEventHandler handler;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestProgressReporter"/> class.
+ /// </summary>
+ /// <param name="handler">The callback handler to be used for reporting progress.</param>
+ public TestProgressReporter(ICallbackEventHandler handler)
+ {
+ this.handler = handler;
+ }
+
+ #region ITestListener Members
+
+ /// <summary>
+ /// Called when a test has just started
+ /// </summary>
+ /// <param name="test">The test that is starting</param>
+ public void TestStarted(ITest test)
+ {
+ string startElement = test is TestSuite
+ ? "start-suite"
+ : "start-test";
+
+ var parent = GetParent(test);
+ try
+ {
+ string report = string.Format(
+ "<{0} id=\"{1}\" parentId=\"{2}\" name=\"{3}\" fullname=\"{4}\"/>",
+ startElement,
+ test.Id,
+ parent != null ? parent.Id : string.Empty,
+ FormatAttributeValue(test.Name),
+ FormatAttributeValue(test.FullName));
+
+ handler.RaiseCallbackEvent(report);
+ }
+ catch (Exception ex)
+ {
+ log.Error("Exception processing " + test.FullName + NUnit.Env.NewLine + ex.ToString());
+ }
+ }
+
+ /// <summary>
+ /// Called when a test has finished. Sends a result summary to the callback.
+ /// to
+ /// </summary>
+ /// <param name="result">The result of the test</param>
+ public void TestFinished(ITestResult result)
+ {
+ try
+ {
+ var node = result.ToXml(false);
+ var parent = GetParent(result.Test);
+ node.Attributes.Add("parentId", parent != null ? parent.Id : string.Empty);
+ handler.RaiseCallbackEvent(node.OuterXml);
+ }
+ catch (Exception ex)
+ {
+ log.Error("Exception processing " + result.FullName + NUnit.Env.NewLine + ex.ToString());
+ }
+ }
+
+ /// <summary>
+ /// Called when a test produces output for immediate display
+ /// </summary>
+ /// <param name="output">A TestOutput object containing the text to display</param>
+ public void TestOutput(TestOutput output)
+ {
+ try
+ {
+ handler.RaiseCallbackEvent(output.ToXml());
+ }
+ catch (Exception ex)
+ {
+ log.Error("Exception processing TestOutput event" + NUnit.Env.NewLine + ex.ToString());
+ }
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ /// <summary>
+ /// Returns the parent test item for the targer test item if it exists
+ /// </summary>
+ /// <param name="test"></param>
+ /// <returns>parent test item</returns>
+ private static ITest GetParent(ITest test)
+ {
+ if (test == null || test.Parent == null)
+ {
+ return null;
+ }
+
+ return test.Parent.IsSuite ? test.Parent : GetParent(test.Parent);
+ }
+
+ /// <summary>
+ /// Makes a string safe for use as an attribute, replacing
+ /// characters characters that can't be used with their
+ /// corresponding xml representations.
+ /// </summary>
+ /// <param name="original">The string to be used</param>
+ /// <returns>A new string with the _values replaced</returns>
+ private static string FormatAttributeValue(string original)
+ {
+ return original
+ .Replace("&", "&")
+ .Replace("\"", """)
+ .Replace("'", "'")
+ .Replace("<", "<")
+ .Replace(">", ">");
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// ParameterizedFixtureSuite serves as a container for the set of test
+ /// fixtures created from a given Type using various parameters.
+ /// </summary>
+ public class ParameterizedFixtureSuite : TestSuite
+ {
+ private bool _genericFixture;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ParameterizedFixtureSuite"/> class.
+ /// </summary>
+ /// <param name="typeInfo">The ITypeInfo for the type that represents the suite.</param>
+ public ParameterizedFixtureSuite(ITypeInfo typeInfo) : base(typeInfo.Namespace, typeInfo.GetDisplayName())
+ {
+ _genericFixture = typeInfo.ContainsGenericParameters;
+ }
+
+ /// <summary>
+ /// Gets a string representing the type of test
+ /// </summary>
+ /// <value></value>
+ public override string TestType
+ {
+ get
+ {
+ return _genericFixture
+ ? "GenericFixture"
+ : "ParameterizedFixture";
+ }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal.Commands;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// ParameterizedMethodSuite holds a collection of individual
+ /// TestMethods with their arguments applied.
+ /// </summary>
+ public class ParameterizedMethodSuite : TestSuite
+ {
+ private bool _isTheory;
+
+ /// <summary>
+ /// Construct from a MethodInfo
+ /// </summary>
+ /// <param name="method"></param>
+ public ParameterizedMethodSuite(IMethodInfo method)
+ : base(method.TypeInfo.FullName, method.Name)
+ {
+ Method = method;
+#if PORTABLE
+ _isTheory = false;
+#else
+ _isTheory = method.IsDefined<TheoryAttribute>(true);
+#endif
+ this.MaintainTestOrder = true;
+ }
+
+ /// <summary>
+ /// Gets a string representing the type of test
+ /// </summary>
+ /// <value></value>
+ public override string TestType
+ {
+ get
+ {
+ if (_isTheory)
+ return "Theory";
+
+ if (this.Method.ContainsGenericParameters)
+ return "GenericMethod";
+
+ return "ParameterizedMethod";
+ }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// SetUpFixture extends TestSuite and supports
+ /// Setup and TearDown methods.
+ /// </summary>
+ public class SetUpFixture : TestSuite, IDisposableFixture
+ {
+ #region Constructor
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SetUpFixture"/> class.
+ /// </summary>
+ /// <param name="type">The type.</param>
+ public SetUpFixture( ITypeInfo type ) : base( type )
+ {
+ this.Name = type.Namespace;
+ if (this.Name == null)
+ this.Name = "[default namespace]";
+ int index = this.Name.LastIndexOf('.');
+ if (index > 0)
+ this.Name = this.Name.Substring(index + 1);
+
+ CheckSetUpTearDownMethods(typeof(OneTimeSetUpAttribute));
+ CheckSetUpTearDownMethods(typeof(OneTimeTearDownAttribute));
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// The Test abstract class represents a test within the framework.
+ /// </summary>
+ public abstract class Test : ITest, IComparable
+ {
+ #region Fields
+
+ /// <summary>
+ /// Static value to seed ids. It's started at 1000 so any
+ /// uninitialized ids will stand out.
+ /// </summary>
+ private static int _nextID = 1000;
+
+ /// <summary>
+ /// The SetUp methods.
+ /// </summary>
+ protected MethodInfo[] setUpMethods;
+
+ /// <summary>
+ /// The teardown methods
+ /// </summary>
+ protected MethodInfo[] tearDownMethods;
+
+ /// <summary>
+ /// Used to cache the declaring type for this MethodInfo
+ /// </summary>
+ protected ITypeInfo DeclaringTypeInfo;
+
+ /// <summary>
+ /// Method property backing field
+ /// </summary>
+ private IMethodInfo _method;
+
+ #endregion
+
+ #region Construction
+
+ /// <summary>
+ /// Constructs a test given its name
+ /// </summary>
+ /// <param name="name">The name of the test</param>
+ protected Test( string name )
+ {
+ Guard.ArgumentNotNullOrEmpty(name, "name");
+
+ Initialize(name);
+ }
+
+ /// <summary>
+ /// Constructs a test given the path through the
+ /// test hierarchy to its parent and a name.
+ /// </summary>
+ /// <param name="pathName">The parent tests full name</param>
+ /// <param name="name">The name of the test</param>
+ protected Test( string pathName, string name )
+ {
+ Guard.ArgumentNotNullOrEmpty(pathName, "pathName");
+
+ Initialize(name);
+
+ FullName = pathName + "." + name;
+ }
+
+ /// <summary>
+ /// TODO: Documentation needed for constructor
+ /// </summary>
+ /// <param name="typeInfo"></param>
+ protected Test(ITypeInfo typeInfo)
+ {
+ Initialize(typeInfo.GetDisplayName());
+
+ string nspace = typeInfo.Namespace;
+ if (nspace != null && nspace != "")
+ FullName = nspace + "." + Name;
+ TypeInfo = typeInfo;
+ }
+
+ /// <summary>
+ /// Construct a test from a MethodInfo
+ /// </summary>
+ /// <param name="method"></param>
+ protected Test(IMethodInfo method)
+ {
+ Initialize(method.Name);
+
+ Method = method;
+ TypeInfo = method.TypeInfo;
+ FullName = method.TypeInfo.FullName + "." + Name;
+ }
+
+ private void Initialize(string name)
+ {
+ FullName = Name = name;
+ Id = GetNextId();
+ Properties = new PropertyBag();
+ RunState = RunState.Runnable;
+ }
+
+ private static string GetNextId()
+ {
+ return IdPrefix + unchecked(_nextID++);
+ }
+
+ #endregion
+
+ #region ITest Members
+
+ /// <summary>
+ /// Gets or sets the id of the test
+ /// </summary>
+ /// <value></value>
+ public string Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the name of the test
+ /// </summary>
+ public string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the fully qualified name of the test
+ /// </summary>
+ /// <value></value>
+ public string FullName { get; set; }
+
+ /// <summary>
+ /// Gets the name of the class where this test was declared.
+ /// Returns null if the test is not associated with a class.
+ /// </summary>
+ public string ClassName
+ {
+ get
+ {
+ ITypeInfo typeInfo = TypeInfo;
+
+ if (Method != null)
+ {
+ if (DeclaringTypeInfo == null)
+ DeclaringTypeInfo = new TypeWrapper(Method.MethodInfo.DeclaringType);
+
+ typeInfo = DeclaringTypeInfo;
+ }
+
+ if (typeInfo == null)
+ return null;
+
+ return typeInfo.IsGenericType
+ ? typeInfo.GetGenericTypeDefinition().FullName
+ : typeInfo.FullName;
+ }
+ }
+
+ /// <summary>
+ /// Gets the name of the method implementing this test.
+ /// Returns null if the test is not implemented as a method.
+ /// </summary>
+ public virtual string MethodName
+ {
+ get { return null; }
+ }
+
+ /// <summary>
+ /// Gets the TypeInfo of the fixture used in running this test
+ /// or null if no fixture type is associated with it.
+ /// </summary>
+ public ITypeInfo TypeInfo { get; private set; }
+
+ /// <summary>
+ /// Gets a MethodInfo for the method implementing this test.
+ /// Returns null if the test is not implemented as a method.
+ /// </summary>
+ public IMethodInfo Method
+ {
+ get { return _method; }
+ set
+ {
+ DeclaringTypeInfo = null;
+ _method = value;
+ }
+ } // public setter needed by NUnitTestCaseBuilder
+
+ /// <summary>
+ /// Whether or not the test should be run
+ /// </summary>
+ public RunState RunState { get; set; }
+
+ /// <summary>
+ /// Gets the name used for the top-level element in the
+ /// XML representation of this test
+ /// </summary>
+ public abstract string XmlElementName { get; }
+
+ /// <summary>
+ /// Gets a string representing the type of test. Used as an attribute
+ /// value in the XML representation of a test and has no other
+ /// function in the framework.
+ /// </summary>
+ public virtual string TestType
+ {
+ get { return this.GetType().Name; }
+ }
+
+ /// <summary>
+ /// Gets a count of test cases represented by
+ /// or contained under this test.
+ /// </summary>
+ public virtual int TestCaseCount
+ {
+ get { return 1; }
+ }
+
+ /// <summary>
+ /// Gets the properties for this test
+ /// </summary>
+ public IPropertyBag Properties { get; private set; }
+
+ /// <summary>
+ /// Returns true if this is a TestSuite
+ /// </summary>
+ public bool IsSuite
+ {
+ get { return this is TestSuite; }
+ }
+
+ /// <summary>
+ /// Gets a bool indicating whether the current test
+ /// has any descendant tests.
+ /// </summary>
+ public abstract bool HasChildren { get; }
+
+ /// <summary>
+ /// Gets the parent as a Test object.
+ /// Used by the core to set the parent.
+ /// </summary>
+ public ITest Parent { get; set; }
+
+ /// <summary>
+ /// Gets this test's child tests
+ /// </summary>
+ /// <value>A list of child tests</value>
+ public abstract System.Collections.Generic.IList<ITest> Tests { get; }
+
+ /// <summary>
+ /// Gets or sets a fixture object for running this test.
+ /// </summary>
+ public virtual object Fixture { get; set; }
+
+ #endregion
+
+ #region Other Public Properties
+
+ /// <summary>
+ /// Static prefix used for ids in this AppDomain.
+ /// Set by FrameworkController.
+ /// </summary>
+ public static string IdPrefix { get; set; }
+
+ /// <summary>
+ /// Gets or Sets the Int value representing the seed for the RandomGenerator
+ /// </summary>
+ /// <value></value>
+ public int Seed { get; set; }
+
+ #endregion
+
+ #region Internal Properties
+
+ internal bool RequiresThread { get; set; }
+
+ internal bool IsAsynchronous { get; set; }
+
+ #endregion
+
+ #region Other Public Methods
+
+ /// <summary>
+ /// Creates a TestResult for this test.
+ /// </summary>
+ /// <returns>A TestResult suitable for this type of test.</returns>
+ public abstract TestResult MakeTestResult();
+
+#if PORTABLE
+ /// <summary>
+ /// Modify a newly constructed test by applying any of NUnit's common
+ /// attributes, based on a supplied ICustomAttributeProvider, which is
+ /// usually the reflection element from which the test was constructed,
+ /// but may not be in some instances. The attributes retrieved are
+ /// saved for use in subsequent operations.
+ /// </summary>
+ /// <param name="provider">An object deriving from MemberInfo</param>
+ public void ApplyAttributesToTest(MemberInfo provider)
+ {
+ //foreach (IApplyToTest iApply in provider.GetAttributes<IApplyToTest>(true))
+ // iApply.ApplyToTest(this);
+ }
+
+ /// <summary>
+ /// Modify a newly constructed test by applying any of NUnit's common
+ /// attributes, based on a supplied ICustomAttributeProvider, which is
+ /// usually the reflection element from which the test was constructed,
+ /// but may not be in some instances. The attributes retrieved are
+ /// saved for use in subsequent operations.
+ /// </summary>
+ /// <param name="provider">An object deriving from MemberInfo</param>
+ public void ApplyAttributesToTest(Assembly provider)
+ {
+ //foreach (IApplyToTest iApply in provider.GetAttributes<IApplyToTest>())
+ // iApply.ApplyToTest(this);
+ }
+#else
+ /// <summary>
+ /// Modify a newly constructed test by applying any of NUnit's common
+ /// attributes, based on a supplied ICustomAttributeProvider, which is
+ /// usually the reflection element from which the test was constructed,
+ /// but may not be in some instances. The attributes retrieved are
+ /// saved for use in subsequent operations.
+ /// </summary>
+ /// <param name="provider">An object implementing ICustomAttributeProvider</param>
+ public void ApplyAttributesToTest(ICustomAttributeProvider provider)
+ {
+ foreach (IApplyToTest iApply in provider.GetCustomAttributes(typeof(IApplyToTest), true))
+ iApply.ApplyToTest(this);
+ }
+#endif
+
+ #endregion
+
+ #region Protected Methods
+
+ /// <summary>
+ /// Add standard attributes and members to a test node.
+ /// </summary>
+ /// <param name="thisNode"></param>
+ /// <param name="recursive"></param>
+ protected void PopulateTestNode(TNode thisNode, bool recursive)
+ {
+ thisNode.AddAttribute("id", this.Id.ToString());
+ thisNode.AddAttribute("name", this.Name);
+ thisNode.AddAttribute("fullname", this.FullName);
+ if (this.MethodName != null)
+ thisNode.AddAttribute("methodname", this.MethodName);
+ if (this.ClassName != null)
+ thisNode.AddAttribute("classname", this.ClassName);
+ thisNode.AddAttribute("runstate", this.RunState.ToString());
+
+ if (Properties.Keys.Count > 0)
+ Properties.AddToXml(thisNode, recursive);
+ }
+
+ #endregion
+
+ #region IXmlNodeBuilder Members
+
+ /// <summary>
+ /// Returns the Xml representation of the test
+ /// </summary>
+ /// <param name="recursive">If true, include child tests recursively</param>
+ /// <returns></returns>
+ public TNode ToXml(bool recursive)
+ {
+ return AddToXml(new TNode("dummy"), recursive);
+ }
+
+ /// <summary>
+ /// Returns an XmlNode representing the current result after
+ /// adding it as a child of the supplied parent node.
+ /// </summary>
+ /// <param name="parentNode">The parent node.</param>
+ /// <param name="recursive">If true, descendant results are included</param>
+ /// <returns></returns>
+ public abstract TNode AddToXml(TNode parentNode, bool recursive);
+
+ #endregion
+
+ #region IComparable Members
+
+ /// <summary>
+ /// Compares this test to another test for sorting purposes
+ /// </summary>
+ /// <param name="obj">The other test</param>
+ /// <returns>Value of -1, 0 or +1 depending on whether the current test is less than, equal to or greater than the other test</returns>
+ public int CompareTo(object obj)
+ {
+ Test other = obj as Test;
+
+ if (other == null)
+ return -1;
+
+ return this.FullName.CompareTo(other.FullName);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2010 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.IO;
+using System.Reflection;
+
+#if PORTABLE
+using Path = NUnit.Compatibility.Path;
+#endif
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// TestAssembly is a TestSuite that represents the execution
+ /// of tests in a managed assembly.
+ /// </summary>
+ public class TestAssembly : TestSuite
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestAssembly"/> class
+ /// specifying the Assembly and the path from which it was loaded.
+ /// </summary>
+ /// <param name="assembly">The assembly this test represents.</param>
+ /// <param name="path">The path used to load the assembly.</param>
+ public TestAssembly(Assembly assembly, string path)
+ : base(path)
+ {
+ this.Assembly = assembly;
+ this.Name = Path.GetFileName(path);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestAssembly"/> class
+ /// for a path which could not be loaded.
+ /// </summary>
+ /// <param name="path">The path used to load the assembly.</param>
+ public TestAssembly(string path) : base(path)
+ {
+ this.Name = Path.GetFileName(path);
+ }
+
+ /// <summary>
+ /// Gets the Assembly represented by this instance.
+ /// </summary>
+ public Assembly Assembly { get; private set; }
+
+ /// <summary>
+ /// Gets the name used for the top-level element in the
+ /// XML representation of this test
+ /// </summary>
+ public override string TestType
+ {
+ get
+ {
+ return "Assembly";
+ }
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// TestFixture is a surrogate for a user test fixture class,
+ /// containing one or more tests.
+ /// </summary>
+ public class TestFixture : TestSuite, IDisposableFixture
+ {
+ #region Constructor
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestFixture"/> class.
+ /// </summary>
+ /// <param name="fixtureType">Type of the fixture.</param>
+ public TestFixture(ITypeInfo fixtureType) : base(fixtureType)
+ {
+ CheckSetUpTearDownMethods(typeof(OneTimeSetUpAttribute));
+ CheckSetUpTearDownMethods(typeof(OneTimeTearDownAttribute));
+ CheckSetUpTearDownMethods(typeof(SetUpAttribute));
+ CheckSetUpTearDownMethods(typeof(TearDownAttribute));
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2012 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections.Generic;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal.Commands;
+using NUnit.Framework.Internal.Execution;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// The TestMethod class represents a Test implemented as a method.
+ /// </summary>
+ public class TestMethod : Test
+ {
+ #region Fields
+
+ /// <summary>
+ /// The ParameterSet used to create this test method
+ /// </summary>
+ internal TestCaseParameters parms;
+
+ #endregion
+
+ #region Constructor
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestMethod"/> class.
+ /// </summary>
+ /// <param name="method">The method to be used as a test.</param>
+ public TestMethod(IMethodInfo method) : base (method) { }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestMethod"/> class.
+ /// </summary>
+ /// <param name="method">The method to be used as a test.</param>
+ /// <param name="parentSuite">The suite or fixture to which the new test will be added</param>
+ public TestMethod(IMethodInfo method, Test parentSuite) : base(method )
+ {
+ // Needed to give proper fullname to test in a parameterized fixture.
+ // Without this, the arguments to the fixture are not included.
+ if (parentSuite != null)
+ FullName = parentSuite.FullName + "." + Name;
+ }
+
+ #endregion
+
+ #region Properties
+
+ internal bool HasExpectedResult
+ {
+ get { return parms != null && parms.HasExpectedResult; }
+ }
+
+ internal object ExpectedResult
+ {
+ get { return parms != null ? parms.ExpectedResult : null; }
+ }
+
+ internal object[] Arguments
+ {
+ get { return parms != null ? parms.Arguments : null; }
+ }
+
+ #endregion
+
+ #region Test Overrides
+
+ /// <summary>
+ /// Overridden to return a TestCaseResult.
+ /// </summary>
+ /// <returns>A TestResult for this test.</returns>
+ public override TestResult MakeTestResult()
+ {
+ return new TestCaseResult(this);
+ }
+
+ /// <summary>
+ /// Gets a bool indicating whether the current test
+ /// has any descendant tests.
+ /// </summary>
+ public override bool HasChildren
+ {
+ get { return false; }
+ }
+
+ /// <summary>
+ /// Returns a TNode representing the current result after
+ /// adding it as a child of the supplied parent node.
+ /// </summary>
+ /// <param name="parentNode">The parent node.</param>
+ /// <param name="recursive">If true, descendant results are included</param>
+ /// <returns></returns>
+ public override TNode AddToXml(TNode parentNode, bool recursive)
+ {
+ TNode thisNode = parentNode.AddElement(XmlElementName);
+
+ PopulateTestNode(thisNode, recursive);
+
+ thisNode.AddAttribute("seed", this.Seed.ToString());
+
+ return thisNode;
+ }
+
+ /// <summary>
+ /// Gets this test's child tests
+ /// </summary>
+ /// <value>A list of child tests</value>
+ public override IList<ITest> Tests
+ {
+ get { return new ITest[0]; }
+ }
+
+ /// <summary>
+ /// Gets the name used for the top-level element in the
+ /// XML representation of this test
+ /// </summary>
+ public override string XmlElementName
+ {
+ get { return "test-case"; }
+ }
+
+ /// <summary>
+ /// Returns the name of the method
+ /// </summary>
+ public override string MethodName
+ {
+ get { return Method.Name; }
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2007 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal.Commands;
+
+#if NET_4_0 || NET_4_5 || PORTABLE
+using System.Threading.Tasks;
+#endif
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// TestSuite represents a composite test, which contains other tests.
+ /// </summary>
+ public class TestSuite : Test
+ {
+ #region Fields
+
+ /// <summary>
+ /// Our collection of child tests
+ /// </summary>
+ private List<ITest> tests = new List<ITest>();
+
+ #endregion
+
+ #region Constructors
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestSuite"/> class.
+ /// </summary>
+ /// <param name="name">The name of the suite.</param>
+ public TestSuite(string name) : base(name)
+ {
+ Arguments = new object[0];
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestSuite"/> class.
+ /// </summary>
+ /// <param name="parentSuiteName">Name of the parent suite.</param>
+ /// <param name="name">The name of the suite.</param>
+ public TestSuite(string parentSuiteName, string name)
+ : base(parentSuiteName, name)
+ {
+ Arguments = new object[0];
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestSuite"/> class.
+ /// </summary>
+ /// <param name="fixtureType">Type of the fixture.</param>
+ public TestSuite(ITypeInfo fixtureType)
+ : base(fixtureType)
+ {
+ Arguments = new object[0];
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TestSuite"/> class.
+ /// </summary>
+ /// <param name="fixtureType">Type of the fixture.</param>
+ public TestSuite(Type fixtureType)
+ : base(new TypeWrapper(fixtureType))
+ {
+ Arguments = new object[0];
+ }
+
+ #endregion
+
+ #region Public Methods
+
+ /// <summary>
+ /// Sorts tests under this suite.
+ /// </summary>
+ public void Sort()
+ {
+ if (!MaintainTestOrder)
+ {
+ this.tests.Sort();
+
+ foreach (Test test in Tests)
+ {
+ TestSuite suite = test as TestSuite;
+ if (suite != null)
+ suite.Sort();
+ }
+ }
+ }
+
+#if false
+ /// <summary>
+ /// Sorts tests under this suite using the specified comparer.
+ /// </summary>
+ /// <param name="comparer">The comparer.</param>
+ public void Sort(IComparer comparer)
+ {
+ this.tests.Sort(comparer);
+
+ foreach( Test test in Tests )
+ {
+ TestSuite suite = test as TestSuite;
+ if ( suite != null )
+ suite.Sort(comparer);
+ }
+ }
+#endif
+
+ /// <summary>
+ /// Adds a test to the suite.
+ /// </summary>
+ /// <param name="test">The test.</param>
+ public void Add(Test test)
+ {
+ test.Parent = this;
+ tests.Add(test);
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Gets this test's child tests
+ /// </summary>
+ /// <value>The list of child tests</value>
+ public override IList<ITest> Tests
+ {
+ get { return tests; }
+ }
+
+ /// <summary>
+ /// Gets a count of test cases represented by
+ /// or contained under this test.
+ /// </summary>
+ /// <value></value>
+ public override int TestCaseCount
+ {
+ get
+ {
+ int count = 0;
+
+ foreach (Test test in Tests)
+ {
+ count += test.TestCaseCount;
+ }
+ return count;
+ }
+ }
+
+ /// <summary>
+ /// The arguments to use in creating the fixture
+ /// </summary>
+ public object[] Arguments { get; internal set; }
+
+ /// <summary>
+ /// Set to true to suppress sorting this suite's contents
+ /// </summary>
+ protected bool MaintainTestOrder { get; set; }
+
+ #endregion
+
+ #region Test Overrides
+
+ /// <summary>
+ /// Overridden to return a TestSuiteResult.
+ /// </summary>
+ /// <returns>A TestResult for this test.</returns>
+ public override TestResult MakeTestResult()
+ {
+ return new TestSuiteResult(this);
+ }
+
+ /// <summary>
+ /// Gets a bool indicating whether the current test
+ /// has any descendant tests.
+ /// </summary>
+ public override bool HasChildren
+ {
+ get
+ {
+ return tests.Count > 0;
+ }
+ }
+
+ /// <summary>
+ /// Gets the name used for the top-level element in the
+ /// XML representation of this test
+ /// </summary>
+ public override string XmlElementName
+ {
+ get { return "test-suite"; }
+ }
+
+ /// <summary>
+ /// Returns an XmlNode representing the current result after
+ /// adding it as a child of the supplied parent node.
+ /// </summary>
+ /// <param name="parentNode">The parent node.</param>
+ /// <param name="recursive">If true, descendant results are included</param>
+ /// <returns></returns>
+ public override TNode AddToXml(TNode parentNode, bool recursive)
+ {
+ TNode thisNode = parentNode.AddElement("test-suite");
+ thisNode.AddAttribute("type", this.TestType);
+
+ PopulateTestNode(thisNode, recursive);
+ thisNode.AddAttribute("testcasecount", this.TestCaseCount.ToString());
+
+
+ if (recursive)
+ foreach (Test test in this.Tests)
+ test.AddToXml(thisNode, recursive);
+
+ return thisNode;
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ /// <summary>
+ /// Check that setup and teardown methods marked by certain attributes
+ /// meet NUnit's requirements and mark the tests not runnable otherwise.
+ /// </summary>
+ /// <param name="attrType">The attribute type to check for</param>
+ protected void CheckSetUpTearDownMethods(Type attrType)
+ {
+ foreach (MethodInfo method in Reflect.GetMethodsWithAttribute(TypeInfo.Type, attrType, true))
+ if (method.IsAbstract ||
+ !method.IsPublic && !method.IsFamily ||
+ method.GetParameters().Length > 0 ||
+ method.ReturnType != typeof(void)
+#if NET_4_0 || NET_4_5 || PORTABLE
+ &&
+ method.ReturnType != typeof(Task)
+#endif
+ )
+ {
+ this.Properties.Set(
+ PropertyNames.SkipReason,
+ string.Format("Invalid signature for SetUp or TearDown method: {0}", method.Name));
+ this.RunState = RunState.NotRunnable;
+ break;
+ }
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !PORTABLE
+using System;
+using System.Threading;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// ThreadUtility provides a set of static methods convenient
+ /// for working with threads.
+ /// </summary>
+ public static class ThreadUtility
+ {
+ /// <summary>
+ /// Do our best to Kill a thread
+ /// </summary>
+ /// <param name="thread">The thread to kill</param>
+ public static void Kill(Thread thread)
+ {
+#if SILVERLIGHT
+ thread.Abort();
+#else
+ Kill(thread, null);
+#endif
+ }
+
+#if !SILVERLIGHT
+ /// <summary>
+ /// Do our best to kill a thread, passing state info
+ /// </summary>
+ /// <param name="thread">The thread to kill</param>
+ /// <param name="stateInfo">Info for the ThreadAbortException handler</param>
+ public static void Kill(Thread thread, object stateInfo)
+ {
+ try
+ {
+ if (stateInfo == null)
+ thread.Abort();
+ else
+ thread.Abort(stateInfo);
+ }
+ catch (ThreadStateException)
+ {
+#if !NETCF
+ // Although obsolete, this use of Resume() takes care of
+ // the odd case where a ThreadStateException is received.
+#pragma warning disable 0618,0612 // Thread.Resume has been deprecated
+ thread.Resume();
+#pragma warning restore 0618,0612 // Thread.Resume has been deprecated
+#endif
+ }
+
+#if !NETCF
+ if ( (thread.ThreadState & ThreadState.WaitSleepJoin) != 0 )
+ thread.Interrupt();
+#endif
+ }
+#endif
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+#if NETCF || PORTABLE
+using System.Linq;
+#endif
+using System.Reflection;
+using System.Text;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// TypeHelper provides static methods that operate on Types.
+ /// </summary>
+ public class TypeHelper
+ {
+ private const int STRING_MAX = 40;
+ private const int STRING_LIMIT = STRING_MAX - 3;
+ private const string THREE_DOTS = "...";
+
+ internal sealed class NonmatchingTypeClass
+ {
+ }
+
+ /// <summary>
+ /// A special value, which is used to indicate that BestCommonType() method
+ /// was unable to find a common type for the specified arguments.
+ /// </summary>
+ public static readonly Type NonmatchingType = typeof( NonmatchingTypeClass );
+
+ /// <summary>
+ /// Gets the display name for a Type as used by NUnit.
+ /// </summary>
+ /// <param name="type">The Type for which a display name is needed.</param>
+ /// <returns>The display name for the Type</returns>
+ public static string GetDisplayName(Type type)
+ {
+ if (type.IsGenericParameter)
+ return type.Name;
+
+ if (type.GetTypeInfo().IsGenericType)
+ {
+ string name = type.FullName;
+ int index = name.IndexOf('[');
+ if (index >= 0) name = name.Substring(0, index);
+
+ index = name.LastIndexOf('.');
+ if (index >= 0) name = name.Substring(index+1);
+
+ var genericArguments = type.GetGenericArguments();
+ var currentArgument = 0;
+
+ StringBuilder sb = new StringBuilder();
+
+ bool firstClassSeen = false;
+ foreach (string nestedClass in name.Split('+'))
+ {
+ if (firstClassSeen)
+ sb.Append("+");
+
+ firstClassSeen = true;
+
+ index = nestedClass.IndexOf('`');
+ if (index >= 0)
+ {
+ var nestedClassName = nestedClass.Substring(0, index);
+ sb.Append(nestedClassName);
+ sb.Append("<");
+
+ var argumentCount = Int32.Parse(nestedClass.Substring(index + 1));
+ for (int i = 0; i < argumentCount; i++)
+ {
+ if (i > 0)
+ sb.Append(",");
+
+ sb.Append(GetDisplayName(genericArguments[currentArgument++]));
+ }
+ sb.Append(">");
+ }
+ else
+ sb.Append(nestedClass);
+ }
+
+ return sb.ToString();
+ }
+
+ int lastdot = type.FullName.LastIndexOf('.');
+ return lastdot >= 0
+ ? type.FullName.Substring(lastdot+1)
+ : type.FullName;
+ }
+
+ /// <summary>
+ /// Gets the display name for a Type as used by NUnit.
+ /// </summary>
+ /// <param name="type">The Type for which a display name is needed.</param>
+ /// <param name="arglist">The arglist provided.</param>
+ /// <returns>The display name for the Type</returns>
+ public static string GetDisplayName(Type type, object[] arglist)
+ {
+ string baseName = GetDisplayName(type);
+ if (arglist == null || arglist.Length == 0)
+ return baseName;
+
+ StringBuilder sb = new StringBuilder( baseName );
+
+ sb.Append("(");
+ for (int i = 0; i < arglist.Length; i++)
+ {
+ if (i > 0) sb.Append(",");
+
+ object arg = arglist[i];
+ string display = arg == null ? "null" : arg.ToString();
+
+ if (arg is double || arg is float)
+ {
+ if (display.IndexOf('.') == -1)
+ display += ".0";
+ display += arg is double ? "d" : "f";
+ }
+ else if (arg is decimal) display += "m";
+ else if (arg is long) display += "L";
+ else if (arg is ulong) display += "UL";
+ else if (arg is string)
+ {
+ if (display.Length > STRING_MAX)
+ display = display.Substring(0, STRING_LIMIT) + THREE_DOTS;
+ display = "\"" + display + "\"";
+ }
+
+ sb.Append(display);
+ }
+ sb.Append(")");
+
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// Returns the best fit for a common type to be used in
+ /// matching actual arguments to a methods Type parameters.
+ /// </summary>
+ /// <param name="type1">The first type.</param>
+ /// <param name="type2">The second type.</param>
+ /// <returns>Either type1 or type2, depending on which is more general.</returns>
+ public static Type BestCommonType(Type type1, Type type2)
+ {
+ if ( type1 == TypeHelper.NonmatchingType ) return TypeHelper.NonmatchingType;
+ if ( type2 == TypeHelper.NonmatchingType ) return TypeHelper.NonmatchingType;
+
+ if (type1 == type2) return type1;
+ if (type1 == null) return type2;
+ if (type2 == null) return type1;
+
+ if (TypeHelper.IsNumeric(type1) && TypeHelper.IsNumeric(type2))
+ {
+ if (type1 == typeof(double)) return type1;
+ if (type2 == typeof(double)) return type2;
+
+ if (type1 == typeof(float)) return type1;
+ if (type2 == typeof(float)) return type2;
+
+ if (type1 == typeof(decimal)) return type1;
+ if (type2 == typeof(decimal)) return type2;
+
+ if (type1 == typeof(UInt64)) return type1;
+ if (type2 == typeof(UInt64)) return type2;
+
+ if (type1 == typeof(Int64)) return type1;
+ if (type2 == typeof(Int64)) return type2;
+
+ if (type1 == typeof(UInt32)) return type1;
+ if (type2 == typeof(UInt32)) return type2;
+
+ if (type1 == typeof(Int32)) return type1;
+ if (type2 == typeof(Int32)) return type2;
+
+ if (type1 == typeof(UInt16)) return type1;
+ if (type2 == typeof(UInt16)) return type2;
+
+ if (type1 == typeof(Int16)) return type1;
+ if (type2 == typeof(Int16)) return type2;
+
+ if (type1 == typeof(byte)) return type1;
+ if (type2 == typeof(byte)) return type2;
+
+ if (type1 == typeof(sbyte)) return type1;
+ if (type2 == typeof(sbyte)) return type2;
+ }
+
+ if ( type1.IsAssignableFrom( type2 ) ) return type1;
+ if ( type2.IsAssignableFrom( type1 ) ) return type2;
+
+ return TypeHelper.NonmatchingType;
+ }
+
+ /// <summary>
+ /// Determines whether the specified type is numeric.
+ /// </summary>
+ /// <param name="type">The type to be examined.</param>
+ /// <returns>
+ /// <c>true</c> if the specified type is numeric; otherwise, <c>false</c>.
+ /// </returns>
+ public static bool IsNumeric(Type type)
+ {
+ return type == typeof(double) ||
+ type == typeof(float) ||
+ type == typeof(decimal) ||
+ type == typeof(Int64) ||
+ type == typeof(Int32) ||
+ type == typeof(Int16) ||
+ type == typeof(UInt64) ||
+ type == typeof(UInt32) ||
+ type == typeof(UInt16) ||
+ type == typeof(byte) ||
+ type == typeof(sbyte);
+ }
+
+ /// <summary>
+ /// Convert an argument list to the required parameter types.
+ /// Currently, only widening numeric conversions are performed.
+ /// </summary>
+ /// <param name="arglist">An array of args to be converted</param>
+ /// <param name="parameters">A ParameterInfo[] whose types will be used as targets</param>
+ public static void ConvertArgumentList(object[] arglist, IParameterInfo[] parameters)
+ {
+ System.Diagnostics.Debug.Assert(arglist.Length <= parameters.Length);
+
+ for (int i = 0; i < arglist.Length; i++)
+ {
+ object arg = arglist[i];
+
+#if PORTABLE
+ if (arg != null)
+#else
+ if (arg != null && arg is IConvertible)
+#endif
+ {
+ Type argType = arg.GetType();
+ Type targetType = parameters[i].ParameterType;
+ bool convert = false;
+
+ if (argType != targetType && !argType.IsAssignableFrom(targetType))
+ {
+ if (IsNumeric(argType) && IsNumeric(targetType))
+ {
+ if (targetType == typeof(double) || targetType == typeof(float))
+ convert = arg is int || arg is long || arg is short || arg is byte || arg is sbyte;
+ else
+ if (targetType == typeof(long))
+ convert = arg is int || arg is short || arg is byte || arg is sbyte;
+ else
+ if (targetType == typeof(short))
+ convert = arg is byte || arg is sbyte;
+ }
+ }
+
+ if (convert)
+ arglist[i] = Convert.ChangeType(arg, targetType,
+ System.Globalization.CultureInfo.InvariantCulture);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Determines whether this instance can deduce type args for a generic type from the supplied arguments.
+ /// </summary>
+ /// <param name="type">The type to be examined.</param>
+ /// <param name="arglist">The arglist.</param>
+ /// <param name="typeArgsOut">The type args to be used.</param>
+ /// <returns>
+ /// <c>true</c> if this the provided args give sufficient information to determine the type args to be used; otherwise, <c>false</c>.
+ /// </returns>
+ public static bool CanDeduceTypeArgsFromArgs(Type type, object[] arglist, ref Type[] typeArgsOut)
+ {
+ Type[] typeParameters = type.GetGenericArguments();
+
+#if NETCF || PORTABLE
+ Type[] argTypes = arglist.Select(a => a == null ? typeof(object) : a.GetType()).ToArray();
+ if (argTypes.Length != typeParameters.Length || argTypes.Any(at => at.GetTypeInfo().IsGenericType))
+ return false;
+ try
+ {
+ type = type.MakeGenericType(argTypes);
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+#endif
+
+ foreach (ConstructorInfo ctor in type.GetConstructors())
+ {
+ ParameterInfo[] parameters = ctor.GetParameters();
+ if (parameters.Length != arglist.Length)
+ continue;
+
+ Type[] typeArgs = new Type[typeParameters.Length];
+ for (int i = 0; i < typeArgs.Length; i++)
+ {
+ for (int j = 0; j < arglist.Length; j++)
+ {
+ if (typeParameters[i].IsGenericParameter || parameters[j].ParameterType.Equals(typeParameters[i]))
+ typeArgs[i] = TypeHelper.BestCommonType(
+ typeArgs[i],
+ arglist[j].GetType());
+ }
+
+ if (typeArgs[i] == null)
+ {
+ typeArgs = null;
+ break;
+ }
+ }
+
+ if (typeArgs != null)
+ {
+ typeArgsOut = typeArgs;
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Gets the _values for an enumeration, using Enum.GetTypes
+ /// where available, otherwise through reflection.
+ /// </summary>
+ /// <param name="enumType"></param>
+ /// <returns></returns>
+ public static Array GetEnumValues(Type enumType)
+ {
+#if NETCF || SILVERLIGHT
+ FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
+
+ Array enumValues = Array.CreateInstance(enumType, fields.Length);
+
+ for (int index = 0; index < fields.Length; index++)
+ enumValues.SetValue(fields[index].GetValue(enumType), index);
+
+ return enumValues;
+#else
+ return Enum.GetValues(enumType);
+#endif
+ }
+
+ /// <summary>
+ /// Gets the ids of the _values for an enumeration,
+ /// using Enum.GetNames where available, otherwise
+ /// through reflection.
+ /// </summary>
+ /// <param name="enumType"></param>
+ /// <returns></returns>
+ public static string[] GetEnumNames(Type enumType)
+ {
+#if NETCF || SILVERLIGHT
+ FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
+
+ string[] names = new string[fields.Length];
+
+ for (int index = 0; index < fields.Length; index++)
+ names[index] = fields[index].Name;
+
+ return names;
+#else
+ return Enum.GetNames(enumType);
+#endif
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Linq;
+using System.Reflection;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+using System.Collections.Generic;
+using System.IO;
+using NUnit.Framework.TUnit;
+
+namespace NUnit.Framework.Internal
+{
+ /// <summary>
+ /// The TypeWrapper class wraps a Type so it may be used in
+ /// a platform-independent manner.
+ /// </summary>
+ public class TypeWrapper : ITypeInfo
+ {
+ /// <summary>
+ /// Construct a TypeWrapper for a specified Type.
+ /// </summary>
+ public TypeWrapper(Type type)
+ {
+ Guard.ArgumentNotNull(type, "Type");
+
+ Type = type;
+ }
+
+ /// <summary>
+ /// Gets the underlying Type on which this TypeWrapper is based.
+ /// </summary>
+ public Type Type { get; private set; }
+
+ /// <summary>
+ /// Gets the base type of this type as an ITypeInfo
+ /// </summary>
+ public ITypeInfo BaseType
+ {
+ get
+ {
+ var baseType = Type.GetTypeInfo().BaseType;
+
+ return baseType != null
+ ? new TypeWrapper(baseType)
+ : null;
+ }
+ }
+
+ /// <summary>
+ /// Gets the Name of the Type
+ /// </summary>
+ public string Name
+ {
+ get { return Type.Name; }
+ }
+
+ /// <summary>
+ /// Gets the FullName of the Type
+ /// </summary>
+ public string FullName
+ {
+ get { return Type.FullName; }
+ }
+
+ /// <summary>
+ /// Gets the assembly in which the type is declared
+ /// </summary>
+ public Assembly Assembly
+ {
+ get { return Type.GetTypeInfo().Assembly; }
+ }
+
+ /// <summary>
+ /// Gets the namespace of the Type
+ /// </summary>
+ public string Namespace
+ {
+ get { return Type.Namespace; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the type is abstract.
+ /// </summary>
+ public bool IsAbstract
+ {
+ get { return Type.GetTypeInfo().IsAbstract; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the Type is a generic Type
+ /// </summary>
+ public bool IsGenericType
+ {
+ get { return Type.GetTypeInfo().IsGenericType; }
+ }
+
+ /// <summary>
+ /// Returns true if the Type wrapped is T
+ /// </summary>
+ public bool IsType(Type type)
+ {
+ return Type == type;
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the Type has generic parameters that have not been replaced by specific Types.
+ /// </summary>
+ public bool ContainsGenericParameters
+ {
+ get { return Type.GetTypeInfo().ContainsGenericParameters; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the Type is a generic Type definition
+ /// </summary>
+ public bool IsGenericTypeDefinition
+ {
+ get { return Type.GetTypeInfo().IsGenericTypeDefinition; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the type is sealed.
+ /// </summary>
+ public bool IsSealed
+ {
+ get { return Type.GetTypeInfo().IsSealed; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this type represents a static class.
+ /// </summary>
+ public bool IsStaticClass
+ {
+ get { return Type.GetTypeInfo().IsSealed && Type.GetTypeInfo().IsAbstract; }
+ }
+
+ /// <summary>
+ /// Get the display name for this type
+ /// </summary>
+ public string GetDisplayName()
+ {
+ return TypeHelper.GetDisplayName(Type);
+ }
+
+ /// <summary>
+ /// Get the display name for an object of this type, constructed with the specified args.
+ /// </summary>
+ public string GetDisplayName(object[] args)
+ {
+ return TypeHelper.GetDisplayName(Type, args);
+ }
+
+ /// <summary>
+ /// Returns a new ITypeInfo representing an instance of this generic Type using the supplied Type arguments
+ /// </summary>
+ public ITypeInfo MakeGenericType(Type[] typeArgs)
+ {
+ return new TypeWrapper(Type.MakeGenericType(typeArgs));
+ }
+
+ /// <summary>
+ /// Returns a Type representing a generic type definition from which this Type can be constructed.
+ /// </summary>
+ public Type GetGenericTypeDefinition()
+ {
+ return Type.GetGenericTypeDefinition();
+ }
+
+ /// <summary>
+ /// Returns an array of custom attributes of the specified type applied to this type
+ /// </summary>
+ public T[] GetCustomAttributes<T>(bool inherit) where T : class
+ {
+#if PORTABLE
+ var allAttribute = Type.GetTypeInfo().GetCustomAttributes();
+ List<string> attributeDic = new List<string>();
+ foreach (Attribute atb in allAttribute)
+ {
+ attributeDic.Add(atb.GetType().FullName);
+ }
+
+ List<T> objects = new List<T>();
+
+ string path = System.IO.Path.GetDirectoryName(Assembly.Location);
+ if (!Directory.Exists(path))
+ {
+ TLogger.WriteError(TLogger.ExceptionTag, "" + path + " - not a directory");
+ return objects.ToArray();
+ }
+ foreach (var assemblyPath in Directory.GetFiles(path, "*.Tests.dll"))
+ {
+ IEnumerable<Type> types;
+ try
+ {
+ Assembly please = AssemblyHelper.Load(assemblyPath);
+ if (please == null) continue;
+ types = please.GetTypes().Where(p => !p.GetTypeInfo().IsAbstract && p.GetTypeInfo().IsClass && p.GetTypeInfo().ImplementedInterfaces.Contains(typeof(T)));
+ }
+ catch (Exception)
+ {
+ continue;
+ }
+ for (int i = 0; i < types.Count(); i++)
+ {
+ try
+ {
+ if (attributeDic.Contains(types.ElementAt(i).FullName))
+ {
+ objects.Add((T)Activator.CreateInstance(types.ElementAt(i)));
+ }
+ }
+ catch (Exception)
+ {
+ }
+ }
+ }
+
+ return objects.ToArray();
+#else
+ return (T[])Type.GetCustomAttributes(typeof(T), inherit);
+#endif
+ }
+
+ /// <summary>
+ /// Returns a value indicating whether the type has an attribute of the specified type.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="inherit"></param>
+ /// <returns></returns>
+ public bool IsDefined<T>(bool inherit)
+ {
+#if PORTABLE
+ return Type.GetTypeInfo().GetCustomAttributes(inherit).Any(a => typeof(T).IsAssignableFrom(a.GetType()));
+#else
+ return Type.GetTypeInfo().IsDefined(typeof(T), inherit);
+#endif
+ }
+
+ /// <summary>
+ /// Returns a flag indicating whether this type has a method with an attribute of the specified type.
+ /// </summary>
+ /// <param name="attributeType"></param>
+ /// <returns></returns>
+ public bool HasMethodWithAttribute(Type attributeType)
+ {
+ return Reflect.HasMethodWithAttribute(Type, attributeType);
+ }
+
+ /// <summary>
+ /// Returns an array of IMethodInfos for methods of this Type
+ /// that match the specified flags.
+ /// </summary>
+ public IMethodInfo[] GetMethods(BindingFlags flags)
+ {
+ var methods = Type.GetMethods(flags);
+ var result = new MethodWrapper[methods.Length];
+
+ for (int i = 0; i < methods.Length; i++)
+ result[i] = new MethodWrapper(Type, methods[i]);
+
+ return result;
+ }
+
+ /// <summary>
+ /// Gets the public constructor taking the specified argument Types
+ /// </summary>
+ public ConstructorInfo GetConstructor(Type[] argTypes)
+ {
+ return Type.GetConstructors()
+ .Where(c => c.GetParameters().ParametersMatch(argTypes))
+ .FirstOrDefault();
+ }
+
+ /// <summary>
+ /// Returns a value indicating whether this Type has a public constructor taking the specified argument Types.
+ /// </summary>
+ public bool HasConstructor(Type[] argTypes)
+ {
+ return GetConstructor(argTypes) != null;
+ }
+
+ /// <summary>
+ /// Construct an object of this Type, using the specified arguments.
+ /// </summary>
+ public object Construct(object[] args)
+ {
+ return Reflect.Construct(Type, args);
+ }
+
+ /// <summary>
+ /// Override ToString() so that error messages in NUnit's own tests make sense
+ /// </summary>
+ public override string ToString()
+ {
+ return Type.ToString();
+ }
+
+ #region extra
+ private string GetAssemblyName(string assemblyFullPath)
+ {
+
+ string[] delimiter1 = { "\\" };
+ string[] delimiter2 = { "/" };
+ string[] delimiterDot = { "." };
+ string[] strAry;
+ string returnValue = "";
+ try
+ {
+ strAry = assemblyFullPath.Split(delimiter1, StringSplitOptions.None);
+
+ if (strAry.Length < 2)
+ strAry = assemblyFullPath.Split(delimiter2, StringSplitOptions.None);
+
+ foreach (string str in strAry)
+ {
+ if (str.Contains("Tests.dll"))
+ {
+ string[] strSplit = str.Split(delimiterDot, StringSplitOptions.None);
+ returnValue = strSplit[0];
+ // LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, "check : "+ returnValue);
+ break;
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, e.ToString());
+ }
+
+ return returnValue;
+ }
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using NUnit.Framework.Constraints;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Helper class with properties and methods that supply
+ /// a number of constraints used in Asserts.
+ /// </summary>
+ public class Is
+ {
+ #region Not
+
+ /// <summary>
+ /// Returns a ConstraintExpression that negates any
+ /// following constraint.
+ /// </summary>
+ public static ConstraintExpression Not
+ {
+ get { return new ConstraintExpression().Not; }
+ }
+
+ #endregion
+
+ #region All
+
+ /// <summary>
+ /// Returns a ConstraintExpression, which will apply
+ /// the following constraint to all members of a collection,
+ /// succeeding if all of them succeed.
+ /// </summary>
+ public static ConstraintExpression All
+ {
+ get { return new ConstraintExpression().All; }
+ }
+
+ #endregion
+
+ #region Null
+
+ /// <summary>
+ /// Returns a constraint that tests for null
+ /// </summary>
+ public static NullConstraint Null
+ {
+ get { return new NullConstraint(); }
+ }
+
+ #endregion
+
+ #region True
+
+ /// <summary>
+ /// Returns a constraint that tests for True
+ /// </summary>
+ public static TrueConstraint True
+ {
+ get { return new TrueConstraint(); }
+ }
+
+ #endregion
+
+ #region False
+
+ /// <summary>
+ /// Returns a constraint that tests for False
+ /// </summary>
+ public static FalseConstraint False
+ {
+ get { return new FalseConstraint(); }
+ }
+
+ #endregion
+
+ #region Positive
+
+ /// <summary>
+ /// Returns a constraint that tests for a positive value
+ /// </summary>
+ public static GreaterThanConstraint Positive
+ {
+ get { return new GreaterThanConstraint(0); }
+ }
+
+ #endregion
+
+ #region Negative
+
+ /// <summary>
+ /// Returns a constraint that tests for a negative value
+ /// </summary>
+ public static LessThanConstraint Negative
+ {
+ get { return new LessThanConstraint(0); }
+ }
+
+ #endregion
+
+ #region Zero
+
+ /// <summary>
+ /// Returns a constraint that tests for equality with zero
+ /// </summary>
+ public static EqualConstraint Zero
+ {
+ get { return new EqualConstraint(0); }
+ }
+
+ #endregion
+
+ #region NaN
+
+ /// <summary>
+ /// Returns a constraint that tests for NaN
+ /// </summary>
+ public static NaNConstraint NaN
+ {
+ get { return new NaNConstraint(); }
+ }
+
+ #endregion
+
+ #region Empty
+
+ /// <summary>
+ /// Returns a constraint that tests for empty
+ /// </summary>
+ public static EmptyConstraint Empty
+ {
+ get { return new EmptyConstraint(); }
+ }
+
+ #endregion
+
+ #region Unique
+
+ /// <summary>
+ /// Returns a constraint that tests whether a collection
+ /// contains all unique items.
+ /// </summary>
+ public static UniqueItemsConstraint Unique
+ {
+ get { return new UniqueItemsConstraint(); }
+ }
+
+ #endregion
+
+ #region BinarySerializable
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Returns a constraint that tests whether an object graph is serializable in binary format.
+ /// </summary>
+ public static BinarySerializableConstraint BinarySerializable
+ {
+ get { return new BinarySerializableConstraint(); }
+ }
+#endif
+
+ #endregion
+
+ #region XmlSerializable
+
+#if !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Returns a constraint that tests whether an object graph is serializable in xml format.
+ /// </summary>
+ public static XmlSerializableConstraint XmlSerializable
+ {
+ get { return new XmlSerializableConstraint(); }
+ }
+#endif
+
+ #endregion
+
+ #region EqualTo
+
+ /// <summary>
+ /// Returns a constraint that tests two items for equality
+ /// </summary>
+ public static EqualConstraint EqualTo(object expected)
+ {
+ return new EqualConstraint(expected);
+ }
+
+ #endregion
+
+ #region SameAs
+
+ /// <summary>
+ /// Returns a constraint that tests that two references are the same object
+ /// </summary>
+ public static SameAsConstraint SameAs(object expected)
+ {
+ return new SameAsConstraint(expected);
+ }
+
+ #endregion
+
+ #region GreaterThan
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is greater than the supplied argument
+ /// </summary>
+ public static GreaterThanConstraint GreaterThan(object expected)
+ {
+ return new GreaterThanConstraint(expected);
+ }
+
+ #endregion
+
+ #region GreaterThanOrEqualTo
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is greater than or equal to the supplied argument
+ /// </summary>
+ public static GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
+ {
+ return new GreaterThanOrEqualConstraint(expected);
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is greater than or equal to the supplied argument
+ /// </summary>
+ public static GreaterThanOrEqualConstraint AtLeast(object expected)
+ {
+ return new GreaterThanOrEqualConstraint(expected);
+ }
+
+ #endregion
+
+ #region LessThan
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is less than the supplied argument
+ /// </summary>
+ public static LessThanConstraint LessThan(object expected)
+ {
+ return new LessThanConstraint(expected);
+ }
+
+ #endregion
+
+ #region LessThanOrEqualTo
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is less than or equal to the supplied argument
+ /// </summary>
+ public static LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
+ {
+ return new LessThanOrEqualConstraint(expected);
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the
+ /// actual value is less than or equal to the supplied argument
+ /// </summary>
+ public static LessThanOrEqualConstraint AtMost(object expected)
+ {
+ return new LessThanOrEqualConstraint(expected);
+ }
+
+ #endregion
+
+ #region TypeOf
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual
+ /// value is of the exact type supplied as an argument.
+ /// </summary>
+ public static ExactTypeConstraint TypeOf(Type expectedType)
+ {
+ return new ExactTypeConstraint(expectedType);
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual
+ /// value is of the exact type supplied as an argument.
+ /// </summary>
+ public static ExactTypeConstraint TypeOf<TExpected>()
+ {
+ return new ExactTypeConstraint(typeof(TExpected));
+ }
+
+ #endregion
+
+ #region InstanceOf
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is of the type supplied as an argument or a derived type.
+ /// </summary>
+ public static InstanceOfTypeConstraint InstanceOf(Type expectedType)
+ {
+ return new InstanceOfTypeConstraint(expectedType);
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is of the type supplied as an argument or a derived type.
+ /// </summary>
+ public static InstanceOfTypeConstraint InstanceOf<TExpected>()
+ {
+ return new InstanceOfTypeConstraint(typeof(TExpected));
+ }
+
+ #endregion
+
+ #region AssignableFrom
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is assignable from the type supplied as an argument.
+ /// </summary>
+ public static AssignableFromConstraint AssignableFrom(Type expectedType)
+ {
+ return new AssignableFromConstraint(expectedType);
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is assignable from the type supplied as an argument.
+ /// </summary>
+ public static AssignableFromConstraint AssignableFrom<TExpected>()
+ {
+ return new AssignableFromConstraint(typeof(TExpected));
+ }
+
+ #endregion
+
+ #region AssignableTo
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is assignable to the type supplied as an argument.
+ /// </summary>
+ public static AssignableToConstraint AssignableTo(Type expectedType)
+ {
+ return new AssignableToConstraint(expectedType);
+ }
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is assignable to the type supplied as an argument.
+ /// </summary>
+ public static AssignableToConstraint AssignableTo<TExpected>()
+ {
+ return new AssignableToConstraint(typeof(TExpected));
+ }
+
+ #endregion
+
+ #region EquivalentTo
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is a collection containing the same elements as the
+ /// collection supplied as an argument.
+ /// </summary>
+ public static CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
+ {
+ return new CollectionEquivalentConstraint(expected);
+ }
+
+ #endregion
+
+ #region SubsetOf
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is a subset of the collection supplied as an argument.
+ /// </summary>
+ public static CollectionSubsetConstraint SubsetOf(IEnumerable expected)
+ {
+ return new CollectionSubsetConstraint(expected);
+ }
+
+ #endregion
+
+ #region SupersetOf
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value
+ /// is a superset of the collection supplied as an argument.
+ /// </summary>
+ public static CollectionSupersetConstraint SupersetOf(IEnumerable expected)
+ {
+ return new CollectionSupersetConstraint(expected);
+ }
+
+ #endregion
+
+ #region Ordered
+
+ /// <summary>
+ /// Returns a constraint that tests whether a collection is ordered
+ /// </summary>
+ public static CollectionOrderedConstraint Ordered
+ {
+ get { return new CollectionOrderedConstraint(); }
+ }
+
+ #endregion
+
+ #region StringContaining
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value contains the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.Contain")]
+ public static SubstringConstraint StringContaining(string expected)
+ {
+ return new SubstringConstraint(expected);
+ }
+
+ #endregion
+
+ #region StringStarting
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value starts with the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.StartWith")]
+ public static StartsWithConstraint StringStarting(string expected)
+ {
+ return new StartsWithConstraint(expected);
+ }
+
+ #endregion
+
+ #region StringEnding
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value ends with the substring supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.EndWith")]
+ public static EndsWithConstraint StringEnding(string expected)
+ {
+ return new EndsWithConstraint(expected);
+ }
+
+ #endregion
+
+ #region StringMatching
+
+ /// <summary>
+ /// Returns a constraint that succeeds if the actual
+ /// value matches the regular expression supplied as an argument.
+ /// </summary>
+ [Obsolete("Deprecated, use Does.Match")]
+ public static RegexConstraint StringMatching(string pattern)
+ {
+ return new RegexConstraint(pattern);
+ }
+
+ #endregion
+
+#if !PORTABLE
+ #region SamePath
+
+ /// <summary>
+ /// Returns a constraint that tests whether the path provided
+ /// is the same as an expected path after canonicalization.
+ /// </summary>
+ public static SamePathConstraint SamePath(string expected)
+ {
+ return new SamePathConstraint(expected);
+ }
+
+ #endregion
+
+ #region SubPath
+
+ /// <summary>
+ /// Returns a constraint that tests whether the path provided
+ /// is a subpath of the expected path after canonicalization.
+ /// </summary>
+ public static SubPathConstraint SubPathOf(string expected)
+ {
+ return new SubPathConstraint(expected);
+ }
+
+ #endregion
+
+ #region SamePathOrUnder
+
+ /// <summary>
+ /// Returns a constraint that tests whether the path provided
+ /// is the same path or under an expected path after canonicalization.
+ /// </summary>
+ public static SamePathOrUnderConstraint SamePathOrUnder(string expected)
+ {
+ return new SamePathOrUnderConstraint(expected);
+ }
+
+ #endregion
+#endif
+
+ #region InRange
+
+ /// <summary>
+ /// Returns a constraint that tests whether the actual value falls
+ /// inclusively within a specified range.
+ /// </summary>
+ /// <remarks>from must be less than or equal to true</remarks>
+ /// <param name="from">Inclusive beginning of the range. Must be less than or equal to to.</param>
+ /// <param name="to">Inclusive end of the range. Must be greater than or equal to from.</param>
+ /// <returns></returns>
+ public static RangeConstraint InRange(IComparable from, IComparable to)
+ {
+ return new RangeConstraint(from, to);
+ }
+
+ #endregion
+
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2008 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using NUnit.Compatibility;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// ListMapper is used to transform a collection used as an actual argument
+ /// producing another collection to be used in the assertion.
+ /// </summary>
+ public class ListMapper
+ {
+ ICollection original;
+
+ /// <summary>
+ /// Construct a ListMapper based on a collection
+ /// </summary>
+ /// <param name="original">The collection to be transformed</param>
+ public ListMapper( ICollection original )
+ {
+ this.original = original;
+ }
+
+ /// <summary>
+ /// Produces a collection containing all the _values of a property
+ /// </summary>
+ /// <param name="name">The collection of property _values</param>
+ /// <returns></returns>
+ public ICollection Property( string name )
+ {
+ var propList = new List<object>();
+ foreach( object item in original )
+ {
+ PropertyInfo property = item.GetType().GetProperty( name,
+ BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance );
+ if ( property == null )
+ throw new ArgumentException( string.Format(
+ "{0} does not have a {1} property", item, name ) );
+
+ propList.Add( property.GetValue( item, null ) );
+ }
+
+ return propList;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// The SpecialValue enum is used to represent TestCase arguments
+ /// that cannot be used as arguments to an Attribute.
+ /// </summary>
+ public enum SpecialValue
+ {
+ /// <summary>
+ /// Null represents a null value, which cannot be used as an
+ /// argument to an attriute under .NET 1.x
+ /// </summary>
+ Null
+ }
+}
--- /dev/null
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Reflection;
+using NUnit.Framework.Internal;
+using System.Threading;
+using NUnit.Framework.Internal.Commands;
+
+namespace NUnit.Framework.TUnit
+{
+ #region tronghieu.d - added class
+ public class TAsyncThreadMgr
+ {
+ private static TAsyncThreadMgr _instance;
+ private static object lockObject = new object();
+
+ public static TAsyncThreadMgr GetInstance()
+ {
+ lock (lockObject)
+ {
+ if (_instance == null)
+ {
+ _instance = new TAsyncThreadMgr();
+ }
+ }
+ return _instance;
+ }
+
+ private TAsyncThreadMgr()
+ {
+ this.testCommand = null;
+ this.testMethod = null;
+ this.arguments = null;
+ this.context = null;
+ }
+
+ public void SetData(TestCommand testCommand, TestMethod testMethod, object[] arguments, TestExecutionContext context, bool IsAsyncOperation)
+ {
+ this.testCommand = testCommand;
+ this.testMethod = testMethod;
+ this.arguments = arguments;
+ this.context = context;
+ this.IsAsyncOperation = IsAsyncOperation;
+ this.exception = null;
+ }
+ #region nguyen.vtan setData for setup & teardown to run on main thread
+ public void SetData(SetUpTearDownItem setupteardownItem)
+ {
+ this._setupteardownItem.Add(setupteardownItem);
+ }
+ public void SetTearDownData(SetUpTearDownItem setupteardownItem)
+ {
+ this._teardownItem.Add(setupteardownItem);
+ }
+ public void ClearSetUpTearDown()
+ {
+ _setupteardownItem.Clear();
+ _teardownItem.Clear();
+ }
+ #endregion
+
+
+ private TestCommand testCommand;
+ private TestMethod testMethod;
+ private object[] arguments;
+ private TestExecutionContext context;
+ private bool IsAsyncOperation;
+ private object result;
+ private Exception exception;
+ readonly List<SetUpTearDownItem> _setupteardownItem = new List<SetUpTearDownItem>();
+ readonly List<SetUpTearDownItem> _teardownItem = new List<SetUpTearDownItem>();
+ //ManualResetEvent _singnalOneTimeTearDown;
+
+ private readonly ManualResetEvent _methodExecutionResetEvent = new ManualResetEvent(false);
+
+ public ManualResetEvent GetMethodExecutionResetEvent()
+ {
+ return _methodExecutionResetEvent;
+ }
+
+ /* Invoke async test method in main thread*/
+ public void RunTestMethod()
+ {
+ if (testCommand == null || testMethod == null || context == null)
+ {
+ return;
+ }
+ TLogger.Write("##### RunTestMethod in TAsyncThreadMgr class #####");
+ if (IsAsyncOperation)
+ RunAsyncTestMethod();
+ else
+ RunNonAsyncTestMethod();
+ }
+
+ public void RunAsyncTestMethod()
+ {
+ TLogger.Write("##### RunAsyncTestMethod in TAsyncThreadMgr class #####");
+ try
+ {
+ result = null;
+ #region nguyen.vtan add Setup
+ runSetup();
+ #endregion
+ result = Reflect.InvokeMethod(testMethod.Method.MethodInfo, context.TestObject, arguments);
+ }
+ catch (Exception e)
+ {
+ exception = e;
+ // Console.WriteLine(e.Message);
+ }
+ finally
+ {
+ if (result == null)
+ {
+ #region nguyen.vtan add Setup
+ runTearDown();
+ Thread.Sleep(50);
+ #endregion
+ testCommand._testMethodRunComplete.Set();
+ _methodExecutionResetEvent.Reset();
+ _methodExecutionResetEvent.WaitOne();
+ RunTestMethod();
+ }
+ else
+ {
+ ((Task)result).GetAwaiter().OnCompleted(() =>
+ {
+ #region nguyen.vtan add TearDown
+ runTearDown();
+ Thread.Sleep(50);
+ #endregion
+ testCommand._testMethodRunComplete.Set();
+ _methodExecutionResetEvent.Reset();
+ _methodExecutionResetEvent.WaitOne();
+ RunTestMethod();
+ });
+ }
+ }
+ }
+
+ public void RunNonAsyncTestMethod()
+ {
+ TLogger.Write("##### RunNonAsyncTestMethod in TAsyncThreadMgr class #####");
+ try
+ {
+ runSetup();
+ result = testMethod.Method.Invoke(context.TestObject, arguments);
+ }
+ catch (Exception ex)
+ {
+ exception = ex;
+ }
+ #region nguyen.vtan add TearDown
+ runTearDown();
+ Thread.Sleep(50);
+ #endregion
+ testCommand._testMethodRunComplete.Set();
+ _methodExecutionResetEvent.Reset();
+ _methodExecutionResetEvent.WaitOne();
+ RunTestMethod();
+ }
+
+ public object GetResult()
+ {
+ return result;
+ }
+
+ public Exception GetNonAsyncMethodException()
+ {
+ return exception;
+ }
+
+ #region add by nguyen.vtan rewrite setup & teardown method to run on main thread
+ public void runSetup()
+ {
+ TLogger.Write("##### runSetup in TAsyncThreadMgr class #####");
+ foreach (var item in _setupteardownItem)
+ {
+ if (item?._setUpMethods != null)
+ foreach (MethodInfo setUpMethod in item._setUpMethods)
+ {
+ item.RunSetUpOrTearDownMethod(context, setUpMethod);
+ }
+ }
+ }
+ public void runTearDown()
+ {
+
+ TLogger.Write("##### runTearDown in TAsyncThreadMgr class #####");
+ if (context?.ExecutionStatus == TestExecutionStatus.AbortRequested)
+ {
+ return;
+ }
+
+ try
+ {
+ foreach (var item in _teardownItem)
+ {
+ // Even though we are only running one level at a time, we
+ // run the teardowns in reverse order to provide consistency.
+ if (item?._tearDownMethods != null)
+ {
+ int index = item._tearDownMethods.Count;
+ while (--index >= 0)
+ {
+ item.RunSetUpOrTearDownMethod(context, item._tearDownMethods[index]);
+ }
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ context.CurrentResult.RecordTearDownException(ex);
+ }
+ }
+ #endregion
+ }
+ #endregion
+}
\ No newline at end of file
--- /dev/null
+// ****************************************************************************************************
+// Namespace: NUnit.Framework.TUnit
+// Class: TLogger
+// Description: Tizen UnitTest Logger
+// Author: Nguyen Truong Duong <duong.nt1@samsung.com>
+// Notes:
+// Revision History:
+// Name: Date: Description:
+// ****************************************************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace NUnit.Framework.TUnit
+{
+ public class TLogger
+ {
+ public static string DefaultTag = "TUnit";
+ public static string TUnitTag = "TUnit";
+ public static string ExceptionTag = "TException";
+
+ public static void Write(string logTag, string message)
+ {
+ Tizen.Log.Info(TUnitTag, message);
+ Console.WriteLine(logTag + message);
+ }
+
+ public static void Write(string message)
+ {
+ Write(DefaultTag, message);
+ }
+
+ public static void WriteError(string message)
+ {
+ Tizen.Log.Error(TUnitTag, message);
+ }
+ public static void WriteError(string tag, string message)
+ {
+ Tizen.Log.Error(tag, message);
+ }
+ }
+
+ public class LogUtils
+ {
+ static public string DEBUG = "D";
+ static public string INFO = "I";
+ static public string ERROR = "E";
+ static public string TAG = "TUnit";
+
+ static public void Write(string level, string tag, string msg)
+ {
+ foreach (string line in msg.Split('\n'))
+ {
+ Console.WriteLine(tag + "[" + level + "] | " + line);
+ WriteDlog(level, tag, line);
+ }
+ }
+
+ static private void WriteDlog(string level, string tag, string msg)
+ {
+ if (level.Equals(DEBUG))
+ {
+ Tizen.Log.Debug(tag, msg);
+ }
+ else if (level.Equals(INFO))
+ {
+ Tizen.Log.Info(tag, msg);
+ }
+ else if (level.Equals(ERROR))
+ {
+ Tizen.Log.Error(tag, msg);
+ }
+ else
+ {
+ Tizen.Log.Info(tag, msg);
+ }
+ }
+ }
+}
--- /dev/null
+// ****************************************************************************************************
+// Namespace: NUnit.Framework.TUnit
+// Class: TSettings
+// Description: Tizen UnitTest Settings
+// Author: Nguyen Truong Duong <duong.nt1@samsung.com>
+// Notes:
+// Revision History:
+// Name: Date: Description:
+// ****************************************************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using System.Net;
+using System.IO;
+using System.Text;
+
+namespace NUnit.Framework.TUnit
+{
+ public class TSettings
+ {
+ private static int DefaultTCDelay = 50; // Default time delay for each test case execution (millisecond) to reduce CPU consumption
+ private static string OutputFilePathName = ""; // XML Result File Path Name
+ public static long CurTCIndex = 0; // HACKING: Curent TC Index
+
+ private static TSettings _instance;
+ private static object lockObject = new object();
+
+ public static TSettings GetInstance()
+ {
+ lock (lockObject)
+ {
+ if (_instance == null)
+ {
+ _instance = new TSettings();
+ }
+ }
+ return _instance;
+ }
+
+ private TSettings()
+ {
+ IsManual = false;
+ }
+
+ public void SetDefaultTCDelay(int defaultTCDelay)
+ {
+ DefaultTCDelay = defaultTCDelay;
+ }
+
+ public int GetDefaultTCDelay()
+ {
+ return DefaultTCDelay;
+ }
+
+ public void SetOutputFilePathName(string outputFilePathName)
+ {
+ OutputFilePathName = outputFilePathName;
+ }
+
+ public string GetOutputFilePathName()
+ {
+ return OutputFilePathName;
+ }
+
+ #region testkit-stub api
+ // [Hyukin.Kwon-code]: session_id for communication with testkit-stub
+ private static bool _isSlaveMode = false;
+ private static int _session_id;
+ private static string _server = "http://127.0.0.1:8000";
+ // private static string _proxy = "http://10.112.1.184:8080/";
+
+ public static bool IsLastTC = false;
+ private static string _testcase_id;
+
+ public void ConnectTestkitStub()
+ {
+ TLogger.Write("############### ConnectTestkitStub ###############");
+ Random rnd = new Random();
+ _session_id = rnd.Next(1000, 9999);
+ _server = "http://127.0.0.1:8000";
+ _isSlaveMode = SyncSessionIdRequest();
+ Console.WriteLine("[TUnitTest] - " + "IsSlaveMode : " + _isSlaveMode);
+ }
+
+ private bool SyncSessionIdRequest()
+ {
+ TLogger.Write("############### In SyncSessionIdRequest ###############");
+ Console.WriteLine("[TUnitTest] - " + "In SyncSessionIdRequest");
+
+ string result = RequestGET("init_session_id", _session_id);
+
+ if (result == null)
+ return false;
+
+ CheckServer();
+
+ //string[] jobj = ResultParser (result);
+ //if (jobj [1] == "OK" && jobj [2] == "1")
+ // return true;
+
+ Dictionary<string, string> dic = parseJson(result);
+
+ if (dic["OK"].Equals("1"))
+ return true;
+ else
+ return false;
+ }
+
+ private bool CheckServer()
+ {
+ TLogger.Write("############### In CheckServer ###############");
+ Console.WriteLine("[TUnitTest] - " + "In CheckServer");
+ string result = RequestGET("check_server");
+
+ if (result == null)
+ return false;
+
+ string[] jobj = ResultParser(result);
+ if (jobj != null)
+ return true;
+ else
+ return false;
+ }
+
+ private string RequestGET(string key)
+ {
+ TLogger.Write("############### In RequestGET ###############");
+ Console.WriteLine("[TUnitTest] - " + "In RequestGET");
+
+ string result = null;
+ string url = _server + "/" + key;
+
+ Console.WriteLine("[TUnitTest] - " + "RequestGET url : " + url);
+ TLogger.Write("############### RequestGET url ###############");
+
+ try
+ {
+ HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
+
+ //Reference
+ // https://msdn.microsoft.com/en-us/library/czdt10d3(v=vs.110).aspx
+
+ WebProxy proxyObject = new WebProxy(_server, true);
+ request.Proxy = proxyObject;
+
+
+ IWebProxy proxy = request.Proxy;
+
+ if (proxy != null)
+ {
+ Console.WriteLine("[TUnitTest] - Proxy is NOT null. Is ByPassed : " + proxy.IsBypassed(new Uri(url)));
+ }
+ else
+ {
+ Console.WriteLine("[TUnitTest] - " + "Proxy is null; no proxy will be used");
+ }
+
+ Task<WebResponse> res = request.GetResponseAsync();
+ res.Wait();
+ WebResponse response = res.Result;
+ Stream stream = response.GetResponseStream();
+ StreamReader reader = new StreamReader(stream);
+ result = reader.ReadToEnd();
+ Console.WriteLine("[TUnitTest] - " + "RequestGET Result : " + result);
+ TLogger.Write("############### RequestGET Result : " + result + " ###############");
+ stream.Dispose();
+ response.Dispose();
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine("[TUnitTest] - " + "RequestGET error : " + e.ToString());
+ }
+
+ return result;
+ }
+
+ private string RequestGET(string key, int sessionId)
+ {
+ TLogger.Write("############### In RequestGET ###############");
+ Console.WriteLine("[TUnitTest] - " + "In RequestGET");
+
+ string result = null;
+ string url = _server + "/" + key + "?session_id=" + _session_id;
+
+ Console.WriteLine("[TUnitTest] - " + "RequestGET url : " + url);
+ TLogger.Write("############### RequestGET url : " + url + " ###############");
+
+ try
+ {
+ HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
+
+ //Reference
+ // https://msdn.microsoft.com/en-us/library/czdt10d3(v=vs.110).aspx
+
+ WebProxy proxyObject = new WebProxy(_server, true);
+ request.Proxy = proxyObject;
+
+
+ IWebProxy proxy = request.Proxy;
+
+ if (proxy != null)
+ {
+ Console.WriteLine("[TUnitTest] - Proxy is NOT null. Is ByPassed : " + proxy.IsBypassed(new Uri(url)));
+ }
+ else
+ {
+ Console.WriteLine("[TUnitTest] - " + "Proxy is null; no proxy will be used");
+ }
+
+ Task<WebResponse> res = request.GetResponseAsync();
+ res.Wait();
+ WebResponse response = res.Result;
+ Stream stream = response.GetResponseStream();
+ StreamReader reader = new StreamReader(stream);
+ result = reader.ReadToEnd();
+ Console.WriteLine("[TUnitTest] - " + "RequestGET Result: " + result);
+ stream.Dispose();
+ response.Dispose();
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine("[TUnitTest] - " + "RequestGET error : " + e.Message);
+ }
+ return result;
+ }
+
+ private string[] ResultParser(string TCID)
+ {
+ string[] delimiter = { "{\"", "\":\"", "\":", ",\"", "\"}", "}" };
+ string[] stringPieces = null;
+
+ try
+ {
+ stringPieces = TCID.Split(delimiter, StringSplitOptions.None);
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine("[TUnitTest] - " + "ResultParser : " + e.Message);
+ }
+
+ return stringPieces;
+ }
+
+ public Dictionary<string, string> parseJson(string jsonString)
+ {
+ Dictionary<string, string> jsonDic = new Dictionary<string, string>();
+ jsonString = jsonString.Replace("\n", "");
+ jsonString = jsonString.Replace("{", "");
+ jsonString = jsonString.Replace("}", "");
+
+ string[] ary = jsonString.Split(',');
+
+ foreach (string item in ary)
+ {
+ if (!item.Equals(""))
+ {
+ string[] keyValue = item.Split(':');
+ keyValue[0] = keyValue[0].Replace(" ", "");
+ keyValue[0] = keyValue[0].Replace("\"", "");
+
+ // 처음 공백 제거
+ while (keyValue[1].StartsWith(" "))
+ keyValue[1] = keyValue[1].Substring(1);
+ // 마지막 공백 제거
+ while (keyValue[1].EndsWith(" "))
+ keyValue[1] = keyValue[1].Substring(0, keyValue[1].Length - 2);
+
+ keyValue[1] = keyValue[1].Replace("\"", "");
+
+ Console.Write(" key : " + keyValue[0] + ", value : " + keyValue[1] + "\n");
+ jsonDic.Add(keyValue[0], keyValue[1].Replace("\"", ""));
+ }
+ }
+
+ return jsonDic;
+ }
+
+ public bool CheckExecutionProgressRequest()
+ {
+ Console.WriteLine("[TUnitTest] - " + "In CheckExecutionProgressRequest");
+
+ string result = RequestGET("check_execution_progress", _session_id);
+
+ if (result == null)
+ return false;
+
+ string[] jobj = ResultParser(result);
+ if (jobj != null)
+ return true;
+ else
+ return false;
+ }
+
+ public bool AskNextStepRequest()
+ {
+ Console.WriteLine("[TUnitTest] - " + "In AskNextStepRequest");
+
+ string result = RequestGET("ask_next_step", _session_id);
+ TLogger.Write("############### In AskNextStepRequest ###############");
+
+ if (result == null)
+ return false;
+
+ Dictionary<string, string> dic = parseJson(result);
+
+ if (dic == null)
+ return false;
+
+ if (dic["step"].Equals("continue"))
+ return true;
+ else
+ return false;
+ }
+
+ public List<string> ManualTestTaskRequest()
+ {
+ List<string> list = new List<string>();
+ string result = RequestGET("manual_cases", _session_id);
+ if (result == null)
+ return list;
+
+ result = result.Replace("[", "");
+ result = result.Replace("]", "");
+ result = result.Replace("\n", "");
+ result = result.Replace("{", "");
+ result = result.Replace("}", "");
+ result = result.Replace(" ", "");
+
+ string[] arr = result.Split(',');
+
+ foreach (string item in arr)
+ {
+ if (!item.Equals("") && item.Contains("case_id"))
+ {
+ string tmp = item.Replace("\"", "");
+ string[] keyValue = tmp.Split(':');
+ list.Add(keyValue[1]);
+ }
+ }
+
+ return list;
+ }
+
+ public string AutoTestTaskRequest()
+ {
+ Console.WriteLine("[TUnitTest] - " + "In AutoTestTaskRequest");
+
+ string result = RequestGET("auto_test_task", _session_id);
+ TLogger.Write("############### In AutoTestTaskRequest ###############");
+ TLogger.Write("");
+ TLogger.Write("");
+ TLogger.Write("");
+
+ if (result == null)
+ return "";
+
+ Dictionary<string, string> dic = parseJson(result);
+
+ if (dic == null)
+ return "";
+
+ if (dic.ContainsKey("none"))
+ IsLastTC = true;
+
+ try
+ {
+ Console.WriteLine("[TUnitTest] - " + "TC name received:[" + dic["case_id"] + "]");
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine("[TUnitTest] - " + "Json parsing Error : " + e.Message);
+ return "";
+ }
+
+ return dic["case_id"];
+
+ }
+ public string RequestPOST(string key, string json)
+ {
+ Console.WriteLine("[TUnitTest] - " + "In RequestPOST");
+ string result = null;
+ TLogger.Write("############### In RequestPOST ###############");
+ string url = _server + "/" + key;
+ json = json + "&session_id=" + _session_id;
+
+ Console.WriteLine("[TUnitTest] - " + "RequestPOST url :" + url);
+
+ try
+ {
+ HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); // WebRequest 객체 형성 및 HttpWebRequest 로 형변환
+
+
+ //Reference
+ // https://msdn.microsoft.com/en-us/library/czdt10d3(v=vs.110).aspx
+
+ WebProxy proxyObject = new WebProxy(_server, true);
+ request.Proxy = proxyObject;
+
+
+ IWebProxy proxy = request.Proxy;
+
+ if (proxy != null)
+ {
+ Console.WriteLine("[TUnitTest] - Proxy is NOT null. Is ByPassed : " + proxy.IsBypassed(new Uri(url)));
+ }
+ else
+ {
+ Console.WriteLine("[TUnitTest] - " + "Proxy is null; no proxy will be used");
+ }
+
+ request.Method = "POST"; // 전송 방법 "GET" or "POST"
+ request.ContentType = "application/json";
+
+ byte[] byteArray = Encoding.UTF8.GetBytes(json);
+
+ Task<Stream> dataAsync = request.GetRequestStreamAsync();
+ dataAsync.Wait();
+ Stream dataStream = dataAsync.Result;
+ dataStream.Write(byteArray, 0, byteArray.Length);
+ dataStream.Dispose();
+
+ Task<WebResponse> resAsync = request.GetResponseAsync();
+ resAsync.Wait();
+
+ WebResponse response = resAsync.Result;
+
+ Stream respPostStream = response.GetResponseStream();
+ StreamReader reader = new StreamReader(respPostStream);
+ result = reader.ReadToEnd();
+
+ Console.WriteLine("[TUnitTest] - " + "###############Asavin############### RequestPOST Result :" + result);
+ reader.Dispose();
+
+ return result;
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine("[TUnitTest] - " + "RequestPOST ERROR :" + e.Message);
+ }
+ return result;
+ }
+
+ public void SubmitManualResult()
+ {
+ TLogger.Write("############### SubmitManualResult ###############");
+ LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG, "Manual test execution done.");
+
+ if (_isSlaveMode == true)
+ {
+ LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG, "Submit result to inform manual execution done.");
+ RequestGET("generate_xml");
+ }
+ }
+
+#if TIZEN
+ public List<string> GetNotPassListManual()
+ {
+ List<string> list = new List<string>();
+ LogUtils.Write(LogUtils.INFO, LogUtils.TAG, "############### GetNotPassListManual ###############");
+ if (AskNextStepRequest())
+ {
+ CheckExecutionProgressRequest();
+ list = ManualTestTaskRequest();
+ }
+ return list;
+ }
+
+ public void NextStepRequest()
+ {
+ TLogger.Write("############### NextStepRequest ###############");
+ if (AskNextStepRequest())
+ {
+ CheckExecutionProgressRequest();
+ }
+ if (AskNextStepRequest())
+ {
+ Testcase_ID = AutoTestTaskRequest();
+ }
+ }
+
+ public SingleTestDoneEventArgs GetSingleTestDoneEventArgs()
+ {
+ SingleTestDoneEventArgs singleTestArgs = new SingleTestDoneEventArgs();
+ singleTestArgs.Name = Testcase_ID;
+ singleTestArgs.Result = TCResult;
+ singleTestArgs.Message = TCMessage;
+ return singleTestArgs;
+ }
+
+ public bool IsSlaveMode
+ {
+ get { return _isSlaveMode; }
+ }
+
+ public bool IsManual
+ {
+ get;
+ set;
+ }
+
+ public string Testcase_ID
+ {
+ get { return _testcase_id; }
+ set { _testcase_id = value; }
+ }
+
+
+ public string TCResult
+ {
+ get;
+ set;
+ }
+
+ public string TCMessage
+ {
+ get;
+ set;
+ }
+
+#endif
+
+ #endregion
+ }
+
+
+ public class SingleTestDoneEventArgs : EventArgs
+ {
+ public string Name { get; set; }
+ public string Result { get; set; }
+ public string Message { get; set; }
+ }
+}
--- /dev/null
+// ****************************************************************************************************
+// Namespace: NUnit.Framework.TUnit
+// Class: TTestMethodCommand
+// Description: Tizen TestMethod Command
+// Author: Nguyen Truong Duong <duong.nt1@samsung.com>
+// Notes:
+// Revision History:
+// Name: Date: Description:
+// ****************************************************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+using System.Threading;
+using NUnit.Framework.Internal;
+using NUnit.Framework.Internal.Commands;
+
+namespace NUnit.Framework.TUnit
+{
+ /// <summary>
+ /// TTestMethodCommand is the lowest level concrete command
+ /// used to run actual test cases.
+ /// </summary>
+ public class TTestMethodCommand : TestCommand
+ {
+ private readonly TestMethod testMethod;
+ private readonly object[] arguments;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TTestMethodCommand"/> class.
+ /// </summary>
+ /// <param name="testMethod">The test.</param>
+ public TTestMethodCommand(TestMethod testMethod)
+ : base(testMethod)
+ {
+ this.testMethod = testMethod;
+ this.arguments = testMethod.Arguments;
+ }
+
+ /// <summary>
+ /// Runs the test, saving a TestResult in the execution context, as
+ /// well as returning it. If the test has an expected result, it
+ /// is asserts on that value. Since failed tests and errors throw
+ /// an exception, this command must be wrapped in an outer command,
+ /// will handle that exception and records the failure. This role
+ /// is usually played by the SetUpTearDown command.
+ /// </summary>
+ /// <param name="context">The execution context</param>
+ public override TestResult Execute(TestExecutionContext context)
+ {
+ // TODO: Decide if we should handle exceptions here
+ object result = RunTestMethod(context);
+
+ if (testMethod.HasExpectedResult)
+ NUnit.Framework.Assert.AreEqual(testMethod.ExpectedResult, result);
+
+ context.CurrentResult.SetResult(ResultState.Success);
+ // TODO: Set assert count here?
+ //context.CurrentResult.AssertCount = context.AssertCount;
+ return context.CurrentResult;
+ }
+
+ private object RunTestMethod(TestExecutionContext context)
+ {
+ // [DuongNT]: Sleep 50 ms to reduce CPU consumption
+ ++TSettings.CurTCIndex;
+ if (TSettings.CurTCIndex % 10 == 0)
+ Thread.Sleep(2000);
+ else
+ Thread.Sleep(TSettings.GetInstance().GetDefaultTCDelay());
+
+ TUnit.TLogger.Write("##### Running Test Case [" + TSettings.CurTCIndex + "]: " + testMethod.Method.TypeInfo.FullName + "." +
+ testMethod.Method.Name);
+
+#if NET_4_0 || NET_4_5 || PORTABLE
+ if (AsyncInvocationRegion.IsAsyncOperation(testMethod.Method.MethodInfo))
+ return RunAsyncTestMethod(context);
+ else
+#endif
+ return RunNonAsyncTestMethod(context);
+ }
+
+#if NET_4_0 || NET_4_5 || PORTABLE || TIZEN
+ private object RunAsyncTestMethod(TestExecutionContext context)
+ {
+ TLogger.Write("##### RunAsyncTestMethod in TTestMethodCommand class #####");
+ #region tronghieu.d - invoke async test method in application thread. This thread is blocked for waiting result.
+ using (AsyncInvocationRegion region = AsyncInvocationRegion.Create(testMethod.Method.MethodInfo))
+ {
+ TAsyncThreadMgr asyncThreadMgr = TAsyncThreadMgr.GetInstance();
+ asyncThreadMgr.SetData(this, testMethod, arguments, context, true);
+ asyncThreadMgr.GetMethodExecutionResetEvent().Set(); // release main thread to invoke method
+ _testMethodRunComplete.WaitOne(); // wait for result in current thread
+ if (asyncThreadMgr.GetNonAsyncMethodException() != null)
+ throw asyncThreadMgr.GetNonAsyncMethodException();
+ try
+ {
+ if (asyncThreadMgr.GetResult() == null)
+ {
+ return asyncThreadMgr.GetResult();
+ }
+ return region.WaitForPendingOperationsToComplete(asyncThreadMgr.GetResult());
+ }
+ catch (Exception e)
+ {
+ throw new NUnitException("Rethrown", e);
+ }
+ }
+ #endregion
+ }
+#endif
+
+ private object RunNonAsyncTestMethod(TestExecutionContext context)
+ {
+ TLogger.Write("##### RunNonAsyncTestMethod in TTestMethodCommand class #####");
+ #region tronghieu.d - invoke async test method in application thread. This thread is blocked for waiting result.
+ TAsyncThreadMgr asyncThreadMgr = TAsyncThreadMgr.GetInstance();
+ asyncThreadMgr.SetData(this, testMethod, arguments, context, false);
+ asyncThreadMgr.GetMethodExecutionResetEvent().Set(); // release main thread to invoke method
+ _testMethodRunComplete.WaitOne(); // wait for result in current thread
+
+ if (asyncThreadMgr.GetNonAsyncMethodException() != null)
+ throw asyncThreadMgr.GetNonAsyncMethodException();
+
+ return asyncThreadMgr.GetResult();
+ #endregion
+ //return testMethod.Method.Invoke(context.TestObject, arguments);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Xml;
+
+namespace NUnit.Framework.TUnit
+{
+ public class XMLUtils
+ {
+ private static string XML_ELEMENT_ENVIRONMENT = "environment";
+ private static string XML_ELEMENT_SUITE = "suite";
+ private static string XML_ELEMENT_SET = "set";
+ private static string XML_ELEMENT_TESTCASE = "testcase";
+ private static string XML_ELEMENT_TEST_ONLOAD_DELAY = "onload_delay";
+ private static string XML_ELEMENT_RESULT = "result";
+
+ private static string XML_ELEMENT_ACTUAL_RESULT = "actual_result";
+ private static string XML_ELEMENT_START = "start";
+ private static string XML_ELEMENT_END = "end";
+ private static string XML_ELEMENT_STDOUT = "stdout";
+ private static string XML_ELEMENT_STDERR = "stderr";
+
+
+ private static string XML_ATTR_NAME_COMPONENT = "component";
+ private static string XML_ATTR_NAME_ELEMENT_EXECUTION_TYPE = "execution_type";
+ private static string XML_ATTR_NAME_ELEMENT_ID = "id";
+ private static string XML_ATTR_NAME_ELEMENT_PRIORITY = "priority";
+ private static string XML_ATTR_NAME_ELEMENT_PURPOSE = "purpose";
+
+
+ /*XML Reader*/
+ private XmlReader reader;
+
+ /* Test Environment */
+ private TestcaseEnvironment testcaseEnv;
+
+ /* Suite Value*/
+ private TestcaseSuite testcaseSuite;
+
+ /* Suite Value*/
+ //private ArrayList tcList;
+
+ private int count;
+
+ private Boolean flag;
+
+
+ // Instance Constructor
+ public XMLUtils()
+ {
+ reader = null;
+ testcaseEnv = new TestcaseEnvironment();
+ testcaseSuite = new TestcaseSuite();
+ count = 0;
+ flag = false;
+ }
+
+ private List<TestcaseData> readXML(string path)
+ {
+ List<TestcaseData> tcList = new List<TestcaseData>();
+
+ reader = null;
+ //reader = new XmlReader.Create(path);
+ reader = XmlReader.Create(path);
+
+ try
+ {
+ while (reader.Read())
+ {
+ switch (reader.NodeType)
+ {
+ case XmlNodeType.Element:
+ if (reader.Name == XML_ELEMENT_ENVIRONMENT)
+ {
+ /* TEST ENVIRONMENT */
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.Name == "build_id")
+ {
+ testcaseEnv.build_id = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"ENV build_id : " + testcaseEnv.build_id);
+ }
+ else if (reader.Name == "device_id")
+ {
+ testcaseEnv.device_id = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"ENV device_id : " + testcaseEnv.device_id);
+ }
+ else if (reader.Name == "device_model")
+ {
+ testcaseEnv.device_model = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"ENV device_model : " + testcaseEnv.device_model);
+ }
+ else if (reader.Name == "device_name")
+ {
+ testcaseEnv.device_name = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"ENV device_name : " + testcaseEnv.device_name);
+ }
+ else if (reader.Name == "lite_version")
+ {
+ testcaseEnv.lite_version = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"ENV lite_version : " + testcaseEnv.lite_version);
+ }
+ else if (reader.Name == "host")
+ {
+ testcaseEnv.host = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"ENV host : " + testcaseEnv.host);
+ }
+ else if (reader.Name == "manufacturer")
+ {
+ testcaseEnv.manufacturer = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"ENV manufacturer : " + testcaseEnv.manufacturer);
+ }
+ else if (reader.Name == "resolution")
+ {
+ testcaseEnv.resolution = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"ENV resolution : " + testcaseEnv.resolution);
+ }
+ else if (reader.Name == "screen_size")
+ {
+ testcaseEnv.screen_size = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"ENV screen_size : " + testcaseEnv.screen_size);
+ }
+ }
+ }
+ /* TEST CASE SUITE */
+ else if (reader.Name == XML_ELEMENT_SUITE)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.Name == "category")
+ {
+ testcaseSuite.suite_category = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"SUITE category : " + testcaseSuite.suite_category);
+ }
+ else if (reader.Name == "launcher")
+ {
+ testcaseSuite.suite_launcher = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"SUITE launcher : " + testcaseSuite.suite_launcher);
+ }
+ else if (reader.Name == "name")
+ {
+ testcaseSuite.suite_name = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"SUITE name : " + testcaseSuite.suite_name);
+ }
+ }
+ }
+ else if (reader.Name == XML_ELEMENT_SET)
+ {
+ reader.MoveToNextAttribute();
+ if (reader.Name == "name")
+ {
+ testcaseSuite.set_name = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"SET name : " + testcaseSuite.set_name);
+ }
+ }
+ /* TEST CASE READ */
+ else if (reader.Name == XML_ELEMENT_TESTCASE)
+ {
+ TestcaseData tmp = new TestcaseData();
+ // add in arrayList
+ tcList.Add(tmp);
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"CASE ARY ADD *****************************");
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.Name == XML_ATTR_NAME_COMPONENT)
+ {
+ ((TestcaseData)tcList[count]).component = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE component : " + reader.Value);
+ }
+ else if (reader.Name == XML_ATTR_NAME_ELEMENT_EXECUTION_TYPE)
+ {
+ ((TestcaseData)tcList[count]).execution_type = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE execution : " + reader.Value);
+ }
+ else if (reader.Name == XML_ATTR_NAME_ELEMENT_ID)
+ {
+ ((TestcaseData)tcList[count]).id = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE ID : " + reader.Value);
+
+ }
+ else if (reader.Name == XML_ATTR_NAME_ELEMENT_PRIORITY)
+ {
+ ((TestcaseData)tcList[count]).priority = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE priority : " + reader.Value);
+ }
+ else if (reader.Name == XML_ATTR_NAME_ELEMENT_PURPOSE)
+ {
+ ((TestcaseData)tcList[count]).purpose = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE purpose : " + reader.Value);
+ }
+ else if (reader.Name == XML_ELEMENT_RESULT)
+ {
+ ((TestcaseData)tcList[count]).result = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE result : " + reader.Value);
+ }
+
+ else if (reader.Name == XML_ELEMENT_TEST_ONLOAD_DELAY)
+ {
+ ((TestcaseData)tcList[count]).onloaddelay = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE onloaddelay : " + reader.Value);
+ }
+ }
+ }
+
+ /* Description */
+ else if (reader.Name == "description")
+ {
+ while (reader.NodeType != XmlNodeType.Text && reader.NodeType != XmlNodeType.EndElement)
+ reader.Read();
+
+ ((TestcaseData)tcList[count]).test_script_entry = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE test_script_entry : " + reader.Value);
+ }
+ /* TEST CASE READ */
+ else if (reader.Name == "result_info")
+ {
+ flag = true;
+ while (flag)
+ {
+ reader.Read();
+ if (reader.NodeType == XmlNodeType.Element)
+ {
+ if (reader.Name == XML_ELEMENT_ACTUAL_RESULT)
+ {
+ while (reader.NodeType != XmlNodeType.Text && reader.NodeType != XmlNodeType.EndElement)
+ reader.Read();
+
+ ((TestcaseData)tcList[count]).actual_result = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE actual_result : " + reader.Value);
+ }
+ else if (reader.Name == XML_ELEMENT_START)
+ {
+ while (reader.NodeType != XmlNodeType.Text && reader.NodeType != XmlNodeType.EndElement)
+ reader.Read();
+
+ ((TestcaseData)tcList[count]).start = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE start : " + reader.Value);
+ }
+ else if (reader.Name == XML_ELEMENT_END)
+ {
+ while (reader.NodeType != XmlNodeType.Text && reader.NodeType != XmlNodeType.EndElement)
+ reader.Read();
+
+ ((TestcaseData)tcList[count]).end = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE end : " + reader.Value);
+ }
+ else if (reader.Name == XML_ELEMENT_STDOUT)
+ {
+ while (reader.NodeType != XmlNodeType.Text && reader.NodeType != XmlNodeType.EndElement)
+ reader.Read();
+
+ ((TestcaseData)tcList[count]).stdout = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE stdout : " + reader.Value);
+ }
+ else if (reader.Name == XML_ELEMENT_STDERR)
+ {
+ while (reader.NodeType != XmlNodeType.Text && reader.NodeType != XmlNodeType.EndElement)
+ reader.Read();
+
+ ((TestcaseData)tcList[count]).stderr = reader.Value;
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE stderr : " + reader.Value);
+ }
+ }
+ if (reader.NodeType == XmlNodeType.EndElement)
+ {
+ if (reader.Name == "result_info")
+ {
+ flag = false;
+ }
+ }
+ }
+ }
+ break;
+ case XmlNodeType.Text:
+ //if (reader.Name == XML_ELEMENT_TEST_SCRIPT_ENTRY)
+ //{
+ //((TestcaseData)tcList[count]).test_script_expected_result = reader.Value;
+ ////LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," CASE test_script_entry : " + reader.Value);
+ ////LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,"CASE ARY END ***************************** ");
+ //}
+ break;
+ case XmlNodeType.EndElement:
+ flag = false;
+ if (reader.Name == "testcase")
+ {
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ," ***************************** END ***************************** ");
+ count++;
+ }
+ break;
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, "ERROR : " + e.Message);
+ }
+
+ reader.Dispose();
+
+ return tcList;
+ }
+
+ public String[] getTestIdList(string path)
+ {
+ List<string> res = new List<string>();
+ List<TestcaseData> tcList;
+
+ try
+ {
+ tcList = readXML(path);
+ foreach (TestcaseData data in tcList)
+ {
+ res.Add(data.id);
+ }
+ }
+ catch (Exception e)
+ {
+ LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, "ERROR : " + e.Message);
+ }
+ return (string[])res.ToArray<string>();
+ }
+
+ public String[] getFailList(string path)
+ {
+
+ List<string> res = new List<string>();
+ List<TestcaseData> tcList;
+
+ try
+ {
+ tcList = readXML(path);
+ foreach (TestcaseData data in tcList)
+ {
+ if (data.result == "FAIL")
+ {
+ res.Add(data.id);
+ //LogUtils.Write(LogUtils.DEBUG, LogUtils.TAG ,data.id);
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, "ERROR : " + e.Message);
+ }
+
+ return (string[])res.ToArray<string>();
+ }
+
+ public void writeResult(String path, String fileName, TestcaseEnvironment testEnv, List<TestcaseData> list)
+ {
+ try
+ {
+ FileStream fs = new FileStream(path + fileName, FileMode.Create);
+ StreamWriter sw = new StreamWriter(fs);
+
+ XmlWriter xmlWriter = XmlWriter.Create(sw);
+ xmlWriter.WriteStartDocument();
+
+ xmlWriter.WriteStartElement("test_definition");
+
+ xmlWriter.WriteStartElement("suite");
+ xmlWriter.WriteAttributeString("category", "");
+ xmlWriter.WriteAttributeString("extension", "");
+ xmlWriter.WriteAttributeString("name", "");
+
+ xmlWriter.WriteStartElement("set");
+ xmlWriter.WriteAttributeString("name", "C#");
+ xmlWriter.WriteAttributeString("set_debug_msg", "N/A");
+ xmlWriter.WriteAttributeString("type", "js");
+
+ /* MAKE TESTCASE */
+ foreach (TestcaseData data in list)
+ {
+
+ xmlWriter.WriteStartElement("testcase");
+ xmlWriter.WriteAttributeString("component", data.component);
+ xmlWriter.WriteAttributeString("execution_type", data.execution_type);
+ xmlWriter.WriteAttributeString("id", data.id);
+ xmlWriter.WriteAttributeString("priority", data.priority);
+ xmlWriter.WriteAttributeString("purpose", data.purpose);
+ xmlWriter.WriteAttributeString("onload_delay", data.onloaddelay);
+ xmlWriter.WriteAttributeString("result", data.result);
+
+ /*
+ <description>
+ <test_script_entry>/opt/tct-messaging-mms-tizen-tests/messaging/MessageBody_mms_extend.html</test_script_entry>
+ </description>
+ */
+ xmlWriter.WriteStartElement("description");
+ xmlWriter.WriteStartElement("test_script_entry");
+ xmlWriter.WriteString(data.test_script_entry);
+ xmlWriter.WriteEndElement(); // close test_script_entry
+ xmlWriter.WriteEndElement(); // close description
+
+ /*
+ <result_info>
+ <actual_result>PASS</actual_result>
+ <start>2016-04-01 16:53:06</start>
+ <end>2016-04-01 16:53:07</end>
+ <stdout>[Message]</stdout>
+ <stderr />
+ </result_info>
+ */
+ xmlWriter.WriteStartElement("result_info");
+
+ xmlWriter.WriteStartElement("actual_result");
+ xmlWriter.WriteString(data.actual_result);
+ xmlWriter.WriteEndElement(); // end of atcual_result
+
+ xmlWriter.WriteStartElement("start");
+ xmlWriter.WriteString(data.start);
+ xmlWriter.WriteEndElement(); // end of start
+
+ xmlWriter.WriteStartElement("end");
+ xmlWriter.WriteString(data.end);
+ xmlWriter.WriteEndElement(); // end of end
+
+ xmlWriter.WriteStartElement("stdout");
+ xmlWriter.WriteString(data.stdout);
+ xmlWriter.WriteEndElement(); // end of stdout
+
+ xmlWriter.WriteStartElement("stderr");
+ xmlWriter.WriteString(data.stderr);
+ xmlWriter.WriteEndElement(); // end of stderr
+
+ xmlWriter.WriteEndElement(); // end of resultinfo
+
+
+ xmlWriter.WriteEndElement(); // end of testcase
+ }
+ xmlWriter.WriteEndElement(); // end of set
+ xmlWriter.WriteEndElement(); // end of suite
+
+ xmlWriter.WriteEndDocument();
+
+ xmlWriter.Dispose();
+
+ sw.Dispose();
+ fs.Dispose();
+ }
+ catch (Exception e)
+ {
+ LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, "ERROR :: : " + e.Message);
+ }
+ }
+
+ /*
+ @fileName : fileName of summary XML
+ @path : path of summary XML
+ @list : SummaryData object list
+ */
+ public void writeSummary(String path, String fileName, List<SummaryData> list)
+ {
+ FileStream fs = new FileStream(path + fileName, FileMode.Create);
+ StreamWriter sw = new StreamWriter(fs);
+
+ XmlWriter xmlWriter = XmlWriter.Create(sw);
+ xmlWriter.WriteStartDocument();
+
+ xmlWriter.WriteStartElement("result_summary");
+ xmlWriter.WriteAttributeString("plan_name", "temp");
+
+
+ /*
+ <environment
+ build_id =""
+ tct_version,"TCT_3.0"
+ tct_profile,"mobile"
+ device_id,"0000d85b00006200"
+ device_model,""
+ device_name,"localhost "
+ host,"Linux-3.13.0-83-generic-x86_64-with-Ubuntu-12.04-precise"
+ resolution,""
+ screen_size,""
+ manufacturer,"">
+ */
+
+ xmlWriter.WriteStartElement("environment");
+ xmlWriter.WriteAttributeString("build_id", "");
+ xmlWriter.WriteAttributeString("tct_version", "TCT_3.0");
+ xmlWriter.WriteAttributeString("tct_profile", "mobile");
+ xmlWriter.WriteAttributeString("device_id", "0000d85b00006200");
+ xmlWriter.WriteAttributeString("device_model", "");
+ xmlWriter.WriteAttributeString("device_name", "localhost");
+ xmlWriter.WriteAttributeString("host", "Linux -3.13.0-83-generic-x86_64-with-Ubuntu-12.04-precise");
+ xmlWriter.WriteAttributeString("resolution", "");
+ xmlWriter.WriteAttributeString("screen_size", "");
+ xmlWriter.WriteAttributeString("manufacturer", "");
+
+
+ //<other xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string" />
+ xmlWriter.WriteStartElement("other");
+ //string attr = "xmlns:xs";
+ //xmlWriter.WriteAttributeString(attr, "http://www.w3.org/2001/XMLSchema");
+ //xmlWriter.WriteAttributeString(attr, "http://www.w3.org/2001/XMLSchema-instance");
+ //xmlWriter.WriteAttributeString("xsi:type", "xs:string");
+ xmlWriter.WriteEndElement(); // close other
+
+ xmlWriter.WriteEndElement(); // close environment
+
+
+ /*
+ <summary test_plan_name = "Empty test_plan_name" >
+ < start_at > 2016 - 04 - 08_18_37_38 </ start_at >
+ < end_at > 2016 - 04 - 08_18_38_07 </ end_at >
+ </ summary >
+ */
+ xmlWriter.WriteStartElement("summary");
+ xmlWriter.WriteAttributeString("test_plan_name", "Empty test_plan_name");
+
+ xmlWriter.WriteStartElement("start_at");
+ xmlWriter.WriteString("2016-04-20_18_37_38");
+ xmlWriter.WriteEndElement(); // close start_at
+
+ xmlWriter.WriteStartElement("end_at");
+ xmlWriter.WriteString("2016 - 04 - 08_18_38_07");
+ xmlWriter.WriteEndElement(); // close end_at
+
+ xmlWriter.WriteEndElement(); // close summary
+
+
+ /*
+ < suite name = "tct-fullscreen-nonw3c-tests" >
+ < total_case > 13 </ total_case >
+ < pass_case > 13 </ pass_case >
+ < pass_rate > 100.00 </ pass_rate >
+ < fail_case > 0 </ fail_case >
+ < fail_rate > 0.00 </ fail_rate >
+ < block_case > 0 </ block_case >
+ < block_rate > 0.00 </ block_rate >
+ < na_case > 0 </ na_case >
+ < na_rate > 0.00 </ na_rate >
+ </ suite >
+ */
+
+ foreach (SummaryData data in list)
+ {
+ xmlWriter.WriteStartElement("suite");
+ xmlWriter.WriteAttributeString("name", data.suiteName);
+
+
+ xmlWriter.WriteStartElement("total_case");
+ xmlWriter.WriteString(data.totalCase+"");
+ xmlWriter.WriteEndElement();// end of total_case
+
+ xmlWriter.WriteStartElement("pass_case");
+ xmlWriter.WriteString(data.passCase + "");
+ xmlWriter.WriteEndElement();// end of pass_case
+
+ xmlWriter.WriteStartElement("pass_rate");
+ xmlWriter.WriteString(data.passRate + "");
+ xmlWriter.WriteEndElement();// end of pass_rate
+
+ xmlWriter.WriteStartElement("fail_case");
+ xmlWriter.WriteString(data.failCase + "");
+ xmlWriter.WriteEndElement();// end of fail_case
+
+ xmlWriter.WriteStartElement("fail_rate");
+ xmlWriter.WriteString(data.failRate + "");
+ xmlWriter.WriteEndElement();// end of fail_rate
+
+ xmlWriter.WriteStartElement("block_case");
+ xmlWriter.WriteString(data.blockCase + "");
+ xmlWriter.WriteEndElement();// end of block_case
+
+ xmlWriter.WriteStartElement("block_rate");
+ xmlWriter.WriteString(data.blockRate + "");
+ xmlWriter.WriteEndElement();// end of block_rate
+
+ xmlWriter.WriteStartElement("na_case");
+ xmlWriter.WriteString(data.naCase + "");
+ xmlWriter.WriteEndElement(); // end of na_case
+
+ xmlWriter.WriteStartElement("na_rate");
+ xmlWriter.WriteString(data.naRate + "");
+ xmlWriter.WriteEndElement();// end of na_reate
+
+ xmlWriter.WriteEndElement(); // end of suite
+
+ }
+
+ xmlWriter.WriteEndDocument(); // end of document
+
+ xmlWriter.Dispose();
+
+
+ sw.Dispose();
+ fs.Dispose();
+ }
+ }
+
+
+ /* Testcase Data */
+ public class TestcaseData
+ {
+ /* testcase value */
+ public String component { get; set; }
+ public String execution_type { get; set; }
+ public String id { get; set; }
+ public String priority { get; set; }
+ public String onloaddelay { get; set; }
+ public String purpose { get; set; }
+ public String test_script_entry { get; set; }
+ public String result { get; set; }
+
+ public String actual_result { get; set; }
+ public String start { get; set; }
+ public String end { get; set; }
+ public String stdout { get; set; }
+ public String stderr { get; set; }
+
+ public TestcaseData()
+ {
+ component = "";
+ execution_type = "";
+ id = "";
+ priority = "";
+ purpose = "";
+ purpose = "";
+ test_script_entry = "";
+ onloaddelay = "";
+ result = "";
+
+ actual_result = "";
+ start = "";
+ end = "";
+ stdout = "";
+ stderr = "";
+ }
+ }
+
+ /* TestcaseSuite Data */
+ public class TestcaseSuite
+ {
+ /*
+ <suite category = "W3C/HTML5 APIs"
+ launcher="WRTLauncher" name="tct-3dtransforms-css3-tests">
+ <set name = "3DTransforms" >
+ */
+ public String suite_category { get; set; }
+ public String suite_launcher { get; set; }
+ public String suite_name { get; set; }
+ public String set_name { get; set; }
+
+ public TestcaseSuite()
+ {
+ suite_category = "";
+ suite_launcher = "";
+ suite_name = "";
+ set_name = "";
+ }
+
+ }
+
+ /* TestcaseEnvironment Data */
+ public class TestcaseEnvironment
+ {
+ /*
+ <suite category = "W3C/HTML5 APIs"
+ launcher="WRTLauncher" name="tct-3dtransforms-css3-tests">
+ <set name = "3DTransforms" >
+ */
+ public String build_id { get; set; }
+ public String device_id { get; set; }
+ public String device_model { get; set; }
+ public String device_name { get; set; }
+
+ public String host { get; set; }
+ public String lite_version { get; set; }
+ public String manufacturer { get; set; }
+ public String resolution { get; set; }
+ public String screen_size { get; set; }
+
+ public TestcaseEnvironment()
+ {
+ build_id = "";
+ device_id = "";
+ device_model = "";
+ device_name = "";
+ device_name = "";
+
+ host = "";
+ lite_version = "";
+ manufacturer = "";
+ resolution = "";
+ screen_size = "";
+ }
+ }
+
+ /* Summary Data */
+ public class SummaryData
+ {
+ public int totalCase { get; set; }
+ public int passCase { get; set; }
+ public int passRate { get; set; }
+ public int failCase { get; set; }
+ public int failRate { get; set; }
+ public int blockCase { get; set; }
+ public int blockRate { get; set; }
+ public int naCase { get; set; }
+ public int naRate { get; set; }
+
+ public string suiteName { get; set; }
+
+ public SummaryData()
+ {
+ totalCase = 0;
+ passCase = 0;
+ passRate = 0;
+ failCase = 0;
+ failRate = 0;
+ blockCase = 0;
+ blockRate = 0;
+ naCase = 0;
+ naRate = 0;
+ suiteName = "";
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+using NUnit.Framework.Constraints;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.Internal.Execution;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Provide the context information of the current test.
+ /// This is an adapter for the internal ExecutionContext
+ /// class, hiding the internals from the user test.
+ /// </summary>
+ public class TestContext
+ {
+ private readonly TestExecutionContext _testExecutionContext;
+ private TestAdapter _test;
+ private ResultAdapter _result;
+
+ #region Constructor
+
+ /// <summary>
+ /// Construct a TestContext for an ExecutionContext
+ /// </summary>
+ /// <param name="testExecutionContext">The ExecutionContext to adapt</param>
+ public TestContext(TestExecutionContext testExecutionContext)
+ {
+ _testExecutionContext = testExecutionContext;
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Get the current test context. This is created
+ /// as needed. The user may save the context for
+ /// use within a test, but it should not be used
+ /// outside the test for which it is created.
+ /// </summary>
+ public static TestContext CurrentContext
+ {
+ get { return new TestContext(TestExecutionContext.CurrentContext); }
+ }
+
+ /// <summary>
+ /// Gets a TextWriter that will send output to the current test result.
+ /// </summary>
+ public static TextWriter Out
+ {
+ get { return TestExecutionContext.CurrentContext.OutWriter; }
+ }
+
+#if !NETCF && !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Gets a TextWriter that will send output directly to Console.Error
+ /// </summary>
+ public static TextWriter Error = new EventListenerTextWriter("Error", Console.Error);
+
+ /// <summary>
+ /// Gets a TextWriter for use in displaying immediate progress messages
+ /// </summary>
+ public static readonly TextWriter Progress = new EventListenerTextWriter("Progress", Console.Error);
+#endif
+
+ /// <summary>
+ /// TestParameters object holds parameters for the test run, if any are specified
+ /// </summary>
+ public static readonly TestParameters Parameters = new TestParameters();
+
+ /// <summary>
+ /// Get a representation of the current test.
+ /// </summary>
+ public TestAdapter Test
+ {
+ get { return _test ?? (_test = new TestAdapter(_testExecutionContext.CurrentTest)); }
+ }
+
+ /// <summary>
+ /// Gets a Representation of the TestResult for the current test.
+ /// </summary>
+ public ResultAdapter Result
+ {
+ get { return _result ?? (_result = new ResultAdapter(_testExecutionContext.CurrentResult)); }
+ }
+
+ /// <summary>
+ /// Gets the unique name of the Worker that is executing this test.
+ /// </summary>
+ public string WorkerId
+ {
+ get { return _testExecutionContext.WorkerId; }
+ }
+#if TIZEN
+#if !SILVERLIGHT && !PORTABLE
+ /// <summary>
+ /// Gets the directory containing the current test assembly.
+ /// </summary>
+ public string TestDirectory
+ {
+ get
+ {
+ Test test = _testExecutionContext.CurrentTest;
+ if (test != null)
+ return AssemblyHelper.GetDirectoryName(test.TypeInfo.Assembly);
+
+ // Test is null, we may be loading tests rather than executing.
+ // Assume that calling assembly is the test assembly.
+ return AssemblyHelper.GetDirectoryName(Assembly.GetCallingAssembly());
+ }
+ }
+#endif
+#endif
+
+ /// <summary>
+ /// Gets the directory to be used for outputting files created
+ /// by this test run.
+ /// </summary>
+ public string WorkDirectory
+ {
+ get { return _testExecutionContext.WorkDirectory; }
+ }
+
+ /// <summary>
+ /// Gets the random generator.
+ /// </summary>
+ /// <value>
+ /// The random generator.
+ /// </value>
+ public Randomizer Random
+ {
+ get { return _testExecutionContext.RandomGenerator; }
+ }
+
+ #endregion
+
+ #region Static Methods
+
+ /// <summary>Write the string representation of a boolean value to the current result</summary>
+ public static void Write(bool value) { Out.Write(value); }
+
+ /// <summary>Write a char to the current result</summary>
+ public static void Write(char value) { Out.Write(value); }
+
+ /// <summary>Write a char array to the current result</summary>
+ public static void Write(char[] value) { Out.Write(value); }
+
+ /// <summary>Write the string representation of a double to the current result</summary>
+ public static void Write(double value) { Out.Write(value); }
+
+ /// <summary>Write the string representation of an Int32 value to the current result</summary>
+ public static void Write(Int32 value) { Out.Write(value); }
+
+ /// <summary>Write the string representation of an Int64 value to the current result</summary>
+ public static void Write(Int64 value) { Out.Write(value); }
+
+ /// <summary>Write the string representation of a decimal value to the current result</summary>
+ public static void Write(decimal value) { Out.Write(value); }
+
+ /// <summary>Write the string representation of an object to the current result</summary>
+ public static void Write(object value) { Out.Write(value); }
+
+ /// <summary>Write the string representation of a Single value to the current result</summary>
+ public static void Write(Single value) { Out.Write(value); }
+
+ /// <summary>Write a string to the current result</summary>
+ public static void Write(string value) { Out.Write(value); }
+
+ /// <summary>Write the string representation of a UInt32 value to the current result</summary>
+ //[CLSCompliant(false)]
+ public static void Write(UInt32 value) { Out.Write(value); }
+
+ /// <summary>Write the string representation of a UInt64 value to the current result</summary>
+ //[CLSCompliant(false)]
+ public static void Write(UInt64 value) { Out.Write(value); }
+
+ /// <summary>Write a formatted string to the current result</summary>
+ public static void Write(string format, object arg1) { Out.Write(format, arg1); }
+
+ /// <summary>Write a formatted string to the current result</summary>
+ public static void Write(string format, object arg1, object arg2) { Out.Write(format, arg1, arg2); }
+
+ /// <summary>Write a formatted string to the current result</summary>
+ public static void Write(string format, object arg1, object arg2, object arg3) { Out.Write(format, arg1, arg2, arg3); }
+
+ /// <summary>Write a formatted string to the current result</summary>
+ public static void Write(string format, params object[] args) { Out.Write(format, args); }
+
+ /// <summary>Write a line terminator to the current result</summary>
+ public static void WriteLine() { Out.WriteLine(); }
+
+ /// <summary>Write the string representation of a boolean value to the current result followed by a line terminator</summary>
+ public static void WriteLine(bool value) { Out.WriteLine(value); }
+
+ /// <summary>Write a char to the current result followed by a line terminator</summary>
+ public static void WriteLine(char value) { Out.WriteLine(value); }
+
+ /// <summary>Write a char array to the current result followed by a line terminator</summary>
+ public static void WriteLine(char[] value) { Out.WriteLine(value); }
+
+ /// <summary>Write the string representation of a double to the current result followed by a line terminator</summary>
+ public static void WriteLine(double value) { Out.WriteLine(value); }
+
+ /// <summary>Write the string representation of an Int32 value to the current result followed by a line terminator</summary>
+ public static void WriteLine(Int32 value) { Out.WriteLine(value); }
+
+ /// <summary>Write the string representation of an Int64 value to the current result followed by a line terminator</summary>
+ public static void WriteLine(Int64 value) { Out.WriteLine(value); }
+
+ /// <summary>Write the string representation of a decimal value to the current result followed by a line terminator</summary>
+ public static void WriteLine(decimal value) { Out.WriteLine(value); }
+
+ /// <summary>Write the string representation of an object to the current result followed by a line terminator</summary>
+ public static void WriteLine(object value) { Out.WriteLine(value); }
+
+ /// <summary>Write the string representation of a Single value to the current result followed by a line terminator</summary>
+ public static void WriteLine(Single value) { Out.WriteLine(value); }
+
+ /// <summary>Write a string to the current result followed by a line terminator</summary>
+ public static void WriteLine(string value) { Out.WriteLine(value); }
+
+ /// <summary>Write the string representation of a UInt32 value to the current result followed by a line terminator</summary>
+ //[CLSCompliant(false)]
+ public static void WriteLine(UInt32 value) { Out.WriteLine(value); }
+
+ /// <summary>Write the string representation of a UInt64 value to the current result followed by a line terminator</summary>
+ //[CLSCompliant(false)]
+ public static void WriteLine(UInt64 value) { Out.WriteLine(value); }
+
+ /// <summary>Write a formatted string to the current result followed by a line terminator</summary>
+ public static void WriteLine(string format, object arg1) { Out.WriteLine(format, arg1); }
+
+ /// <summary>Write a formatted string to the current result followed by a line terminator</summary>
+ public static void WriteLine(string format, object arg1, object arg2) { Out.WriteLine(format, arg1, arg2); }
+
+ /// <summary>Write a formatted string to the current result followed by a line terminator</summary>
+ public static void WriteLine(string format, object arg1, object arg2, object arg3) { Out.WriteLine(format, arg1, arg2, arg3); }
+
+ /// <summary>Write a formatted string to the current result followed by a line terminator</summary>
+ public static void WriteLine(string format, params object[] args) { Out.WriteLine(format, args); }
+
+ /// <summary>
+ /// This method adds the a new ValueFormatterFactory to the
+ /// chain of responsibility used for fomatting values in messages.
+ /// The scope of the change is the current TestContext.
+ /// </summary>
+ /// <param name="formatterFactory">The factory delegate</param>
+ public static void AddFormatter(ValueFormatterFactory formatterFactory)
+ {
+ TestExecutionContext.CurrentContext.AddFormatter(formatterFactory);
+ }
+
+ /// <summary>
+ /// This method provides a simplified way to add a ValueFormatter
+ /// delegate to the chain of responsibility, creating the factory
+ /// delegate internally. It is useful when the Type of the object
+ /// is the only criterion for selection of the formatter, since
+ /// it can be used without getting involved with a compould function.
+ /// </summary>
+ /// <typeparam name="TSUPPORTED">The type supported by this formatter</typeparam>
+ /// <param name="formatter">The ValueFormatter delegate</param>
+ public static void AddFormatter<TSUPPORTED>(ValueFormatter formatter)
+ {
+ AddFormatter(next => val => (val is TSUPPORTED) ? formatter(val) : next(val));
+ }
+
+ #endregion
+
+ #region Nested TestAdapter Class
+
+ /// <summary>
+ /// TestAdapter adapts a Test for consumption by
+ /// the user test code.
+ /// </summary>
+ public class TestAdapter
+ {
+ private readonly Test _test;
+
+ #region Constructor
+
+ /// <summary>
+ /// Construct a TestAdapter for a Test
+ /// </summary>
+ /// <param name="test">The Test to be adapted</param>
+ public TestAdapter(Test test)
+ {
+ _test = test;
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Gets the unique Id of a test
+ /// </summary>
+ public String ID
+ {
+ get { return _test.Id; }
+ }
+
+ /// <summary>
+ /// The name of the test, which may or may not be
+ /// the same as the method name.
+ /// </summary>
+ public string Name
+ {
+ get { return _test.Name; }
+ }
+
+ /// <summary>
+ /// The name of the method representing the test.
+ /// </summary>
+ public string MethodName
+ {
+ get
+ {
+ return _test is TestMethod
+ ? _test.Method.Name
+ : null;
+ }
+ }
+
+ /// <summary>
+ /// The FullName of the test
+ /// </summary>
+ public string FullName
+ {
+ get { return _test.FullName; }
+ }
+
+ /// <summary>
+ /// The ClassName of the test
+ /// </summary>
+ public string ClassName
+ {
+ get { return _test.ClassName; }
+ }
+
+ /// <summary>
+ /// The properties of the test.
+ /// </summary>
+ public IPropertyBag Properties
+ {
+ get { return _test.Properties; }
+ }
+
+ #endregion
+ }
+
+ #endregion
+
+ #region Nested ResultAdapter Class
+
+ /// <summary>
+ /// ResultAdapter adapts a TestResult for consumption by
+ /// the user test code.
+ /// </summary>
+ public class ResultAdapter
+ {
+ private readonly TestResult _result;
+
+ #region Constructor
+
+ /// <summary>
+ /// Construct a ResultAdapter for a TestResult
+ /// </summary>
+ /// <param name="result">The TestResult to be adapted</param>
+ public ResultAdapter(TestResult result)
+ {
+ _result = result;
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Gets a ResultState representing the outcome of the test.
+ /// </summary>
+ public ResultState Outcome
+ {
+ get { return _result.ResultState; }
+ }
+
+ /// <summary>
+ /// Gets the message associated with a test
+ /// failure or with not running the test
+ /// </summary>
+ public string Message
+ {
+ get { return _result.Message; }
+ }
+
+ /// <summary>
+ /// Gets any stacktrace associated with an
+ /// error or failure.
+ /// </summary>
+ public virtual string StackTrace
+ {
+ get { return _result.StackTrace; }
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that failed
+ /// when running the test and all its children.
+ /// </summary>
+ public int FailCount
+ {
+ get { return _result.FailCount; }
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that passed
+ /// when running the test and all its children.
+ /// </summary>
+ public int PassCount
+ {
+ get { return _result.PassCount; }
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that were skipped
+ /// when running the test and all its children.
+ /// </summary>
+ public int SkipCount
+ {
+ get { return _result.SkipCount; }
+ }
+
+ /// <summary>
+ /// Gets the number of test cases that were inconclusive
+ /// when running the test and all its children.
+ /// </summary>
+ public int InconclusiveCount
+ {
+ get { return _result.InconclusiveCount; }
+ }
+
+ #endregion
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// TestParameters class holds any named parameters supplied to the test run
+ /// </summary>
+ public class TestParameters
+ {
+ private readonly Dictionary<string, string> _parameters = new Dictionary<string, string>();
+
+ /// <summary>
+ /// Gets the number of test parameters
+ /// </summary>
+ public int Count
+ {
+ get { return _parameters.Count; }
+ }
+
+ /// <summary>
+ /// Gets a collection of the test parameter names
+ /// </summary>
+ public ICollection<string> Names
+ {
+ get { return _parameters.Keys; }
+ }
+
+ /// <summary>
+ /// Gets a flag indicating whether a parameter with the specified name exists.N
+ /// </summary>
+ /// <param name="name">Name of the parameter</param>
+ /// <returns>True if it exists, otherwise false</returns>
+ public bool Exists(string name)
+ {
+ return _parameters.ContainsKey(name);
+ }
+
+ /// <summary>
+ /// Indexer provides access to the internal dictionary
+ /// </summary>
+ /// <param name="name">Name of the parameter</param>
+ /// <returns>Value of the parameter or null if not present</returns>
+ public string this[string name]
+ {
+ get { return Get(name); }
+ }
+
+ /// <summary>
+ /// Get method is a simple alternative to the indexer
+ /// </summary>
+ /// <param name="name">Name of the paramter</param>
+ /// <returns>Value of the parameter or null if not present</returns>
+ public string Get(string name)
+ {
+ return Exists(name) ? _parameters[name] : null;
+ }
+
+ /// <summary>
+ /// Get the value of a parameter or a default string
+ /// </summary>
+ /// <param name="name">Name of the parameter</param>
+ /// <param name="defaultValue">Default value of the parameter</param>
+ /// <returns>Value of the parameter or default value if not present</returns>
+ public string Get(string name, string defaultValue)
+ {
+ return Get(name) ?? defaultValue;
+ }
+
+ /// <summary>
+ /// Get the value of a parameter or return a default
+ /// </summary>
+ /// <typeparam name="T">The return Type</typeparam>
+ /// <param name="name">Name of the parameter</param>
+ /// <param name="defaultValue">Default value of the parameter</param>
+ /// <returns>Value of the parameter or default value if not present</returns>
+ public T Get<T>(string name, T defaultValue)
+ {
+ string val = Get(name);
+ return val != null ? (T)Convert.ChangeType(val, typeof(T), null) : defaultValue;
+ }
+
+ /// <summary>
+ /// Adds a parameter to the list
+ /// </summary>
+ /// <param name="name">Name of the parameter</param>
+ /// <param name="value">Value of the parameter</param>
+ internal void Add(string name, string value)
+ {
+ _parameters[name] = value;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2009 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+
+using System;
+using System.Collections;
+using NUnit.Framework.Constraints;
+
+namespace NUnit.Framework
+{
+ /// <summary>
+ /// Helper class with properties and methods that supply
+ /// constraints that operate on exceptions.
+ /// </summary>
+ public class Throws
+ {
+ #region Exception
+
+ /// <summary>
+ /// Creates a constraint specifying an expected exception
+ /// </summary>
+ public static ResolvableConstraintExpression Exception
+ {
+ get { return new ConstraintExpression().Append(new ThrowsOperator()); }
+ }
+
+ #endregion
+
+ #region InnerException
+
+ /// <summary>
+ /// Creates a constraint specifying an exception with a given InnerException
+ /// </summary>
+ public static ResolvableConstraintExpression InnerException
+ {
+ get { return Exception.InnerException; }
+ }
+
+ #endregion
+
+ #region TargetInvocationException
+
+ /// <summary>
+ /// Creates a constraint specifying an expected TargetInvocationException
+ /// </summary>
+ public static ExactTypeConstraint TargetInvocationException
+ {
+ get { return TypeOf(typeof(System.Reflection.TargetInvocationException)); }
+ }
+
+ #endregion
+
+ #region ArgumentException
+
+ /// <summary>
+ /// Creates a constraint specifying an expected ArgumentException
+ /// </summary>
+ public static ExactTypeConstraint ArgumentException
+ {
+ get { return TypeOf(typeof(System.ArgumentException)); }
+ }
+
+ #endregion
+
+ #region ArgumentNullException
+
+ /// <summary>
+ /// Creates a constraint specifying an expected ArgumentNUllException
+ /// </summary>
+ public static ExactTypeConstraint ArgumentNullException
+ {
+ get { return TypeOf(typeof (System.ArgumentNullException)); }
+ }
+
+ #endregion
+
+ #region InvalidOperationException
+
+ /// <summary>
+ /// Creates a constraint specifying an expected InvalidOperationException
+ /// </summary>
+ public static ExactTypeConstraint InvalidOperationException
+ {
+ get { return TypeOf(typeof(System.InvalidOperationException)); }
+ }
+
+ #endregion
+
+ #region Nothing
+
+ /// <summary>
+ /// Creates a constraint specifying that no exception is thrown
+ /// </summary>
+ public static ThrowsNothingConstraint Nothing
+ {
+ get { return new ThrowsNothingConstraint(); }
+ }
+
+ #endregion
+
+ #region TypeOf
+
+ /// <summary>
+ /// Creates a constraint specifying the exact type of exception expected
+ /// </summary>
+ public static ExactTypeConstraint TypeOf(Type expectedType)
+ {
+ return Exception.TypeOf(expectedType);
+ }
+
+ /// <summary>
+ /// Creates a constraint specifying the exact type of exception expected
+ /// </summary>
+ public static ExactTypeConstraint TypeOf<TExpected>()
+ {
+ return TypeOf(typeof(TExpected));
+ }
+
+ #endregion
+
+ #region InstanceOf
+
+ /// <summary>
+ /// Creates a constraint specifying the type of exception expected
+ /// </summary>
+ public static InstanceOfTypeConstraint InstanceOf(Type expectedType)
+ {
+ return Exception.InstanceOf(expectedType);
+ }
+
+ /// <summary>
+ /// Creates a constraint specifying the type of exception expected
+ /// </summary>
+ public static InstanceOfTypeConstraint InstanceOf<TExpected>()
+ {
+ return InstanceOf(typeof(TExpected));
+ }
+
+ #endregion
+
+ }
+}
--- /dev/null
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <OutputType>Library</OutputType>
+ <TargetFramework>netstandard2.0</TargetFramework>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\..\..\src\Tizen.Applications.Common\Tizen.Applications.Common.csproj" />
+ <ProjectReference Include="..\..\..\src\Tizen.Log\Tizen.Log.csproj" />
+ <ProjectReference Include="..\..\..\src\Tizen.NUI.Components\Tizen.NUI.Components.csproj" />
+ <ProjectReference Include="..\..\..\src\Tizen.NUI\Tizen.NUI.csproj" />
+ </ItemGroup>
+
+</Project>
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using NUnit.Common;
+
+namespace NUnitLite
+{
+ /// <summary>
+ /// NUnitLiteOptions encapsulates the option settings for NUnitLite.
+ /// Currently, there are no additional options beyond those common
+ /// options that are shared with nunit3-console. If NUnitLite should
+ /// acquire some unique options, they should be placed here.
+ /// </summary>
+ public class NUnitLiteOptions : CommandLineOptions
+ {
+ /// <summary>
+ /// Constructor
+ /// </summary>
+ public NUnitLiteOptions(params string[] args) : base(args) { }
+
+ // Currently used only by test
+ //public NUnitLiteOptions(IDefaultOptionsProvider provider, params string[] args) : base(provider, args) { }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+using System.Xml;
+using NUnit.Common;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnitLite
+{
+ /// <summary>
+ /// OutputManager is responsible for creating output files
+ /// from a test run in various formats.
+ /// </summary>
+ public class OutputManager
+ {
+ private string _workDirectory;
+
+ /// <summary>
+ /// Construct an OutputManager
+ /// </summary>
+ /// <param name="workDirectory">The directory to use for reports</param>
+ public OutputManager(string workDirectory)
+ {
+ _workDirectory = workDirectory;
+ }
+
+ /// <summary>
+ /// Write the result of a test run according to a spec.
+ /// </summary>
+ /// <param name="result">The test result</param>
+ /// <param name="spec">An output specification</param>
+ /// <param name="runSettings">Settings</param>
+ /// <param name="filter">Filter</param>
+ public void WriteResultFile(ITestResult result, OutputSpecification spec, IDictionary<string, object> runSettings, TestFilter filter)
+ {
+ string outputPath = Path.Combine(_workDirectory, spec.OutputPath);
+ OutputWriter outputWriter = null;
+
+ switch (spec.Format)
+ {
+ case "nunit3":
+ outputWriter = new NUnit3XmlOutputWriter();
+ break;
+
+ case "nunit2":
+ outputWriter = new NUnit2XmlOutputWriter();
+ break;
+
+ //case "user":
+ // Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
+ // string dir = Path.GetDirectoryName(uri.LocalPath);
+ // outputWriter = new XmlTransformOutputWriter(Path.Combine(dir, spec.Transform));
+ // break;
+
+ default:
+ throw new ArgumentException(
+ string.Format("Invalid XML output format '{0}'", spec.Format),
+ "spec");
+ }
+
+ outputWriter.WriteResultFile(result, outputPath, runSettings, filter);
+ Console.WriteLine("Results ({0}) saved as {1}", spec.Format, outputPath);
+ }
+
+ /// <summary>
+ /// Write out the result of exploring the tests
+ /// </summary>
+ /// <param name="test">The top-level test</param>
+ /// <param name="spec">An OutputSpecification</param>
+ public void WriteTestFile(ITest test, OutputSpecification spec)
+ {
+ string outputPath = Path.Combine(_workDirectory, spec.OutputPath);
+ OutputWriter outputWriter = null;
+
+ switch (spec.Format)
+ {
+ case "nunit3":
+ outputWriter = new NUnit3XmlOutputWriter();
+ break;
+
+ case "cases":
+ outputWriter = new TestCaseOutputWriter();
+ break;
+
+ //case "user":
+ // Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
+ // string dir = Path.GetDirectoryName(uri.LocalPath);
+ // outputWriter = new XmlTransformOutputWriter(Path.Combine(dir, spec.Transform));
+ // break;
+
+ default:
+ throw new ArgumentException(
+ string.Format("Invalid XML output format '{0}'", spec.Format),
+ "spec");
+ }
+
+ outputWriter.WriteTestFile(test, outputPath);
+ Console.WriteLine("Tests ({0}) saved as {1}", spec.Format, outputPath);
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Reflection;
+using System.Xml;
+using System.IO;
+using NUnit.Common;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnitLite
+{
+ /// <summary>
+ /// NUnit2XmlOutputWriter is able to create an xml file representing
+ /// the result of a test run in NUnit 2.x format.
+ /// </summary>
+ public class NUnit2XmlOutputWriter : OutputWriter
+ {
+ private XmlWriter xmlWriter;
+
+ /// <summary>
+ /// Write info about a test
+ /// </summary>
+ /// <param name="test">The test</param>
+ /// <param name="writer">A TextWriter</param>
+ public override void WriteTestFile(ITest test, TextWriter writer)
+ {
+ throw new NotImplementedException("Explore test output is not supported by the NUnit2 format.");
+ }
+
+ /// <summary>
+ /// Writes the result of a test run to a specified TextWriter.
+ /// </summary>
+ /// <param name="result">The test result for the run</param>
+ /// <param name="writer">The TextWriter to which the xml will be written</param>
+ /// <param name="runSettings"></param>
+ /// <param name="filter"></param>
+ public override void WriteResultFile(ITestResult result, TextWriter writer, IDictionary<string, object> runSettings, TestFilter filter)
+ {
+ // NOTE: Under .NET 1.1, XmlTextWriter does not implement IDisposable,
+ // but does implement Close(). Hence we cannot use a 'using' clause.
+ //using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
+#if SILVERLIGHT
+ XmlWriter xmlWriter = XmlWriter.Create(writer);
+#else
+ //XmlW xmlWriter = new XmlTextWriter(writer);
+ //xmlWriter.Formatting = Formatting.Indented;
+ XmlWriter xmlWriter = XmlWriter.Create(writer);
+#endif
+
+ try
+ {
+ WriteXmlOutput(result, xmlWriter);
+ }
+ finally
+ {
+ //writer.Close();
+ }
+ }
+
+ private void WriteXmlOutput(ITestResult result, XmlWriter xmlWriter)
+ {
+ this.xmlWriter = xmlWriter;
+
+ InitializeXmlFile(result);
+ WriteResultElement(result);
+ TerminateXmlFile();
+ }
+
+ private void InitializeXmlFile(ITestResult result)
+ {
+ ResultSummary summary = new ResultSummary(result);
+
+ xmlWriter.WriteStartDocument(false);
+ xmlWriter.WriteComment("This file represents the results of running a test suite");
+
+ xmlWriter.WriteStartElement("test-results");
+
+ xmlWriter.WriteAttributeString("name", result.FullName);
+ xmlWriter.WriteAttributeString("total", summary.TestCount.ToString());
+ xmlWriter.WriteAttributeString("errors", summary.ErrorCount.ToString());
+ xmlWriter.WriteAttributeString("failures", summary.FailureCount.ToString());
+ var notRunTotal = summary.SkipCount + summary.FailureCount + summary.InvalidCount;
+ xmlWriter.WriteAttributeString("not-run", notRunTotal.ToString());
+ xmlWriter.WriteAttributeString("inconclusive", summary.InconclusiveCount.ToString());
+ xmlWriter.WriteAttributeString("ignored", summary.IgnoreCount.ToString());
+ xmlWriter.WriteAttributeString("skipped", summary.SkipCount.ToString());
+ xmlWriter.WriteAttributeString("invalid", summary.InvalidCount.ToString());
+
+ xmlWriter.WriteAttributeString("date", result.StartTime.ToString("yyyy-MM-dd"));
+ xmlWriter.WriteAttributeString("time", result.StartTime.ToString("HH:mm:ss"));
+ WriteEnvironment();
+ WriteCultureInfo();
+ }
+
+ private void WriteCultureInfo()
+ {
+ xmlWriter.WriteStartElement("culture-info");
+ xmlWriter.WriteAttributeString("current-culture",
+ CultureInfo.CurrentCulture.ToString());
+ xmlWriter.WriteAttributeString("current-uiculture",
+ CultureInfo.CurrentUICulture.ToString());
+ xmlWriter.WriteEndElement();
+ }
+
+ private void WriteEnvironment()
+ {
+// xmlWriter.WriteStartElement("environment");
+// var assemblyName = AssemblyHelper.GetAssemblyName(Assembly.GetExecutingAssembly());
+// xmlWriter.WriteAttributeString("nunit-version",
+// assemblyName.Version.ToString());
+// xmlWriter.WriteAttributeString("clr-version",
+// Environment.Version.ToString());
+// xmlWriter.WriteAttributeString("os-version",
+// Environment.OSVersion.ToString());
+// xmlWriter.WriteAttributeString("platform",
+// Environment.OSVersion.Platform.ToString());
+//#if !NETCF
+// xmlWriter.WriteAttributeString("cwd",
+// Environment.CurrentDirectory);
+//#if !SILVERLIGHT
+// xmlWriter.WriteAttributeString("machine-name",
+// Environment.MachineName);
+// xmlWriter.WriteAttributeString("user",
+// Environment.UserName);
+// xmlWriter.WriteAttributeString("user-domain",
+// Environment.UserDomainName);
+//#endif
+//#endif
+// xmlWriter.WriteEndElement();
+ }
+
+ private void WriteResultElement(ITestResult result)
+ {
+ StartTestElement(result);
+
+ WriteCategories(result);
+ WriteProperties(result);
+
+ switch (result.ResultState.Status)
+ {
+ case TestStatus.Skipped:
+ if (result.Message != null)
+ WriteReasonElement(result.Message);
+ break;
+ case TestStatus.Failed:
+ WriteFailureElement(result.Message, result.StackTrace);
+ break;
+ }
+
+ if (result.Test is TestSuite)
+ WriteChildResults(result);
+
+ xmlWriter.WriteEndElement(); // test element
+ }
+
+ private void TerminateXmlFile()
+ {
+ xmlWriter.WriteEndElement(); // test-results
+ xmlWriter.WriteEndDocument();
+ xmlWriter.Flush();
+ //xmlWriter.Close();
+ }
+
+
+ #region Element Creation Helpers
+
+ private void StartTestElement(ITestResult result)
+ {
+ ITest test = result.Test;
+ TestSuite suite = test as TestSuite;
+
+ if (suite != null)
+ {
+ xmlWriter.WriteStartElement("test-suite");
+ xmlWriter.WriteAttributeString("type", suite.TestType == "ParameterizedMethod" ? "ParameterizedTest" : suite.TestType);
+ xmlWriter.WriteAttributeString("name", suite.TestType == "Assembly" || suite.TestType == "Project"
+ ? result.Test.FullName
+ : result.Test.Name);
+ }
+ else
+ {
+ xmlWriter.WriteStartElement("test-case");
+ xmlWriter.WriteAttributeString("name", result.Name);
+ }
+
+ if (test.Properties.ContainsKey(PropertyNames.Description))
+ {
+ string description = (string)test.Properties.Get(PropertyNames.Description);
+ xmlWriter.WriteAttributeString("description", description);
+ }
+
+ TestStatus status = result.ResultState.Status;
+ string translatedResult = TranslateResult(result.ResultState);
+
+ if (status != TestStatus.Skipped)
+ {
+ xmlWriter.WriteAttributeString("executed", "True");
+ xmlWriter.WriteAttributeString("result", translatedResult);
+ xmlWriter.WriteAttributeString("success", status == TestStatus.Passed ? "True" : "False");
+ xmlWriter.WriteAttributeString("time", result.Duration.ToString("0.000", NumberFormatInfo.InvariantInfo));
+ xmlWriter.WriteAttributeString("asserts", result.AssertCount.ToString());
+ }
+ else
+ {
+ xmlWriter.WriteAttributeString("executed", "False");
+ xmlWriter.WriteAttributeString("result", translatedResult);
+ }
+ }
+
+ private string TranslateResult(ResultState resultState)
+ {
+ switch (resultState.Status)
+ {
+ default:
+ case TestStatus.Passed:
+ return "Success";
+ case TestStatus.Inconclusive:
+ return "Inconclusive";
+ case TestStatus.Failed:
+ switch (resultState.Label)
+ {
+ case "Error":
+ case "Cancelled":
+ return resultState.Label;
+ default:
+ return "Failure";
+ }
+ case TestStatus.Skipped:
+ switch (resultState.Label)
+ {
+ case "Ignored":
+ return "Ignored";
+ case "Invalid":
+ return "NotRunnable";
+ default:
+ return "Skipped";
+ }
+ }
+ }
+
+ private void WriteCategories(ITestResult result)
+ {
+ IPropertyBag properties = result.Test.Properties;
+
+ if (properties.ContainsKey(PropertyNames.Category))
+ {
+ xmlWriter.WriteStartElement("categories");
+
+ foreach (string category in properties[PropertyNames.Category])
+ {
+ xmlWriter.WriteStartElement("category");
+ xmlWriter.WriteAttributeString("name", category);
+ xmlWriter.WriteEndElement();
+ }
+
+ xmlWriter.WriteEndElement();
+ }
+ }
+
+ private void WriteProperties(ITestResult result)
+ {
+ IPropertyBag properties = result.Test.Properties;
+ int nprops = 0;
+
+ foreach (string key in properties.Keys)
+ {
+ if (key != PropertyNames.Category)
+ {
+ if (nprops++ == 0)
+ xmlWriter.WriteStartElement("properties");
+
+ foreach (object prop in properties[key])
+ {
+ xmlWriter.WriteStartElement("property");
+ xmlWriter.WriteAttributeString("name", key);
+ xmlWriter.WriteAttributeString("value", prop.ToString());
+ xmlWriter.WriteEndElement();
+ }
+ }
+ }
+
+ if (nprops > 0)
+ xmlWriter.WriteEndElement();
+ }
+
+ private void WriteReasonElement(string message)
+ {
+ xmlWriter.WriteStartElement("reason");
+ xmlWriter.WriteStartElement("message");
+ WriteCData(message);
+ xmlWriter.WriteEndElement();
+ xmlWriter.WriteEndElement();
+ }
+
+ private void WriteFailureElement(string message, string stackTrace)
+ {
+ xmlWriter.WriteStartElement("failure");
+ xmlWriter.WriteStartElement("message");
+ WriteCData(message);
+ xmlWriter.WriteEndElement();
+ xmlWriter.WriteStartElement("stack-trace");
+ if (stackTrace != null)
+ WriteCData(stackTrace);
+ xmlWriter.WriteEndElement();
+ xmlWriter.WriteEndElement();
+ }
+
+ private void WriteChildResults(ITestResult result)
+ {
+ xmlWriter.WriteStartElement("results");
+
+ foreach (ITestResult childResult in result.Children)
+ WriteResultElement(childResult);
+
+ xmlWriter.WriteEndElement();
+ }
+
+ #endregion
+
+ #region Output Helpers
+ ///// <summary>
+ ///// Makes string safe for xml parsing, replacing control chars with '?'
+ ///// </summary>
+ ///// <param name="encodedString">string to make safe</param>
+ ///// <returns>xml safe string</returns>
+ //private static string CharacterSafeString(string encodedString)
+ //{
+ // /*The default code page for the system will be used.
+ // Since all code pages use the same lower 128 bytes, this should be sufficient
+ // for finding unprintable control characters that make the xslt processor error.
+ // We use characters encoded by the default code page to avoid mistaking bytes as
+ // individual characters on non-latin code pages.*/
+ // char[] encodedChars = System.Text.Encoding.Default.GetChars(System.Text.Encoding.Default.GetBytes(encodedString));
+
+ // System.Collections.ArrayList pos = new System.Collections.ArrayList();
+ // for (int x = 0; x < encodedChars.Length; x++)
+ // {
+ // char currentChar = encodedChars[x];
+ // //unprintable characters are below 0x20 in Unicode tables
+ // //some control characters are acceptable. (carriage return 0x0D, line feed 0x0A, horizontal tab 0x09)
+ // if (currentChar < 32 && (currentChar != 9 && currentChar != 10 && currentChar != 13))
+ // {
+ // //save the array index for later replacement.
+ // pos.Add(x);
+ // }
+ // }
+ // foreach (int index in pos)
+ // {
+ // encodedChars[index] = '?';//replace unprintable control characters with ?(3F)
+ // }
+ // return System.Text.Encoding.Default.GetString(System.Text.Encoding.Default.GetBytes(encodedChars));
+ //}
+
+ private void WriteCData(string text)
+ {
+ int start = 0;
+ while (true)
+ {
+ int illegal = text.IndexOf("]]>", start);
+ if (illegal < 0)
+ break;
+ xmlWriter.WriteCData(text.Substring(start, illegal - start + 2));
+ start = illegal + 2;
+ if (start >= text.Length)
+ return;
+ }
+
+ if (start > 0)
+ xmlWriter.WriteCData(text.Substring(start));
+ else
+ xmlWriter.WriteCData(text);
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Reflection;
+using System.Xml;
+using NUnit.Common;
+using NUnit.Framework.Api;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnitLite
+{
+ /// <summary>
+ /// NUnit3XmlOutputWriter is responsible for writing the results
+ /// of a test to a file in NUnit 3.0 format.
+ /// </summary>
+ public class NUnit3XmlOutputWriter : OutputWriter
+ {
+ /// <summary>
+ /// Writes test info to the specified TextWriter
+ /// </summary>
+ /// <param name="test">The test to be written</param>
+ /// <param name="writer">A TextWriter to which the test info is written</param>
+ public override void WriteTestFile(ITest test, TextWriter writer)
+ {
+ XmlWriterSettings settings = new XmlWriterSettings();
+ settings.Indent = true;
+
+ using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
+ {
+ test.ToXml(true).WriteTo(xmlWriter);
+ }
+ }
+
+ /// <summary>
+ /// Writes the test result to the specified TextWriter
+ /// </summary>
+ /// <param name="result">The result to be written to a file</param>
+ /// <param name="writer">A TextWriter to which the result is written</param>
+ /// <param name="runSettings"></param>
+ /// <param name="filter"></param>
+ public override void WriteResultFile(ITestResult result, TextWriter writer, IDictionary<string, object> runSettings, TestFilter filter)
+ {
+ XmlWriterSettings xmlSettings = new XmlWriterSettings();
+ xmlSettings.Indent = true;
+
+ using (XmlWriter xmlWriter = XmlWriter.Create(writer, xmlSettings))
+ {
+ WriteXmlResultOutput(result, xmlWriter, runSettings, filter);
+ }
+ }
+
+ private void WriteXmlResultOutput(ITestResult result, XmlWriter xmlWriter, IDictionary<string, object> runSettings, TestFilter filter)
+ {
+ TNode resultNode = result.ToXml(true);
+
+ // Insert elements as first child in reverse order
+ if (runSettings != null) // Some platforms don't have settings
+ FrameworkController.InsertSettingsElement(resultNode, runSettings);
+#if !SILVERLIGHT
+ //FrameworkController.InsertEnvironmentElement(resultNode);
+#endif
+
+ TNode testRun = MakeTestRunElement(result);
+
+#if !SILVERLIGHT && !NETCF
+ //testRun.ChildNodes.Add(MakeCommandLineElement());
+#endif
+ testRun.ChildNodes.Add(MakeTestFilterElement(filter));
+ testRun.ChildNodes.Add(resultNode);
+
+ testRun.WriteTo(xmlWriter);
+ }
+
+ private TNode MakeTestRunElement(ITestResult result)
+ {
+ TNode testRun = new TNode("test-run");
+
+ testRun.AddAttribute("id", "2");
+ testRun.AddAttribute("name", result.Name);
+ testRun.AddAttribute("fullname", result.FullName);
+ testRun.AddAttribute("testcasecount", result.Test.TestCaseCount.ToString());
+
+ testRun.AddAttribute("result", result.ResultState.Status.ToString());
+ if (result.ResultState.Label != string.Empty)
+ testRun.AddAttribute("label", result.ResultState.Label);
+
+ testRun.AddAttribute("start-time", result.StartTime.ToString("u"));
+ testRun.AddAttribute("end-time", result.EndTime.ToString("u"));
+ testRun.AddAttribute("duration", result.Duration.ToString("0.000000", NumberFormatInfo.InvariantInfo));
+
+ testRun.AddAttribute("total", (result.PassCount + result.FailCount + result.SkipCount + result.InconclusiveCount).ToString());
+ testRun.AddAttribute("passed", result.PassCount.ToString());
+ testRun.AddAttribute("failed", result.FailCount.ToString());
+ testRun.AddAttribute("inconclusive", result.InconclusiveCount.ToString());
+ testRun.AddAttribute("skipped", result.SkipCount.ToString());
+ testRun.AddAttribute("asserts", result.AssertCount.ToString());
+
+ testRun.AddAttribute("random-seed", Randomizer.InitialSeed.ToString());
+
+ // NOTE: The console runner adds attributes for engine-version and clr-version
+ // Neither of these is needed under nunitlite since there is no engine involved
+ // and we are running under the same runtime as the tests.
+
+ return testRun;
+ }
+
+#if !SILVERLIGHT && !NETCF
+ //private static TNode MakeCommandLineElement()
+ //{
+ // return new TNode("command-line", Environment.CommandLine, true);
+ //}
+#endif
+
+ private static TNode MakeTestFilterElement(TestFilter filter)
+ {
+ TNode result = new TNode("filter");
+ if (!filter.IsEmpty)
+ filter.AddToXml(result, true);
+ return result;
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnitLite
+{
+ /// <summary>
+ /// OutputWriter is an abstract class used to write test
+ /// results to a file in various formats. Specific
+ /// OutputWriters are derived from this class.
+ /// </summary>
+ public abstract class OutputWriter
+ {
+ /// <summary>
+ /// Writes a test result to a file
+ /// </summary>
+ /// <param name="result">The result to be written</param>
+ /// <param name="outputPath">Path to the file to which the result is written</param>
+ /// <param name="runSettings">A dictionary of settings used for this test run</param>
+ public void WriteResultFile(ITestResult result, string outputPath, IDictionary<string, object> runSettings, TestFilter filter)
+ {
+ FileStream fs = new FileStream(outputPath, FileMode.CreateNew);
+ using (StreamWriter writer = new StreamWriter(fs))
+ {
+ WriteResultFile(result, writer, runSettings, filter);
+ }
+ }
+
+ /// <summary>
+ /// Writes test info to a file
+ /// </summary>
+ /// <param name="test">The test to be written</param>
+ /// <param name="outputPath">Path to the file to which the test info is written</param>
+ public void WriteTestFile(ITest test, string outputPath)
+ {
+ FileStream fs = new FileStream(outputPath, FileMode.CreateNew);
+ using (StreamWriter writer = new StreamWriter(fs))
+ {
+ WriteTestFile(test, writer);
+ }
+ }
+
+ /// <summary>
+ /// Abstract method that writes a test result to a TextWriter
+ /// </summary>
+ /// <param name="result">The result to be written</param>
+ /// <param name="writer">A TextWriter to which the result is written</param>
+ /// <param name="runSettings">A dictionary of settings used for this test run</param>
+ /// <param name="filter"></param>
+ public abstract void WriteResultFile(ITestResult result, TextWriter writer, IDictionary<string, object> runSettings, TestFilter filter);
+
+ /// <summary>
+ /// Abstract method that writes test info to a TextWriter
+ /// </summary>
+ /// <param name="test">The test to be written</param>
+ /// <param name="writer">A TextWriter to which the test info is written</param>
+ public abstract void WriteTestFile(ITest test, TextWriter writer);
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2011 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+
+namespace NUnitLite
+{
+ /// <summary>
+ /// TestCaseOutputWriter lists test cases
+ /// </summary>
+ public class TestCaseOutputWriter : OutputWriter
+ {
+ /// <summary>
+ /// Write a list of test cases to a file
+ /// </summary>
+ /// <param name="test"></param>
+ /// <param name="writer"></param>
+ public override void WriteTestFile(ITest test, TextWriter writer)
+ {
+ if (test.IsSuite)
+ foreach (var child in test.Tests)
+ WriteTestFile(child, writer);
+ else
+ writer.WriteLine(test.FullName);
+ }
+
+ /// <summary>
+ /// Write a list of test cases to a file
+ /// </summary>
+ /// <param name="result"></param>
+ /// <param name="writer"></param>
+ /// <param name="runSettings"></param>
+ /// <param name="filter"></param>
+ public override void WriteResultFile(ITestResult result, TextWriter writer, IDictionary<string, object> runSettings, TestFilter filter)
+ {
+ WriteTestFile(result.Test, writer);
+ }
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014-2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using NUnit.Framework.Interfaces;
+
+namespace NUnitLite
+{
+ /// <summary>
+ /// Helper class used to summarize the result of a test run
+ /// </summary>
+ public class ResultSummary
+ {
+ #region Constructor
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ResultSummary"/> class.
+ /// </summary>
+ /// <param name="result">The result.</param>
+ public ResultSummary(ITestResult result)
+ {
+ InitializeCounters();
+
+ ResultState = result.ResultState;
+ StartTime = result.StartTime;
+ EndTime = result.EndTime;
+ Duration = result.Duration;
+
+ Summarize(result);
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Gets the number of test cases for which results
+ /// have been summarized. Any tests excluded by use of
+ /// Category or Explicit attributes are not counted.
+ /// </summary>
+ public int TestCount { get; private set; }
+
+ /// <summary>
+ /// Returns the number of test cases actually run.
+ /// </summary>
+ public int RunCount
+ {
+ get { return PassCount + ErrorCount + FailureCount + InconclusiveCount; }
+ }
+
+ /// <summary>
+ /// Gets the number of tests not run for any reason.
+ /// </summary>
+ public int NotRunCount
+ {
+ get { return InvalidCount + SkipCount + IgnoreCount + ExplicitCount; }
+ }
+
+ /// <summary>
+ /// Returns the number of failed test cases (including errors and invalid tests)
+ /// </summary>
+ public int FailedCount
+ {
+ get { return FailureCount + InvalidCount + ErrorCount; }
+ }
+
+ /// <summary>
+ /// Returns the sum of skipped test cases, including ignored and explicit tests
+ /// </summary>
+ public int TotalSkipCount
+ {
+ get { return SkipCount + IgnoreCount + ExplicitCount; }
+ }
+
+ /// <summary>
+ /// Gets the count of passed tests
+ /// </summary>
+ public int PassCount { get; private set; }
+
+ /// <summary>
+ /// Gets count of failed tests, excluding errors and invalid tests
+ /// </summary>
+ public int FailureCount { get; private set; }
+
+ /// <summary>
+ /// Gets the error count
+ /// </summary>
+ public int ErrorCount { get; private set; }
+
+ /// <summary>
+ /// Gets the count of inconclusive tests
+ /// </summary>
+ public int InconclusiveCount { get; private set; }
+
+ /// <summary>
+ /// Returns the number of test cases that were not runnable
+ /// due to errors in the signature of the class or method.
+ /// Such tests are also counted as Errors.
+ /// </summary>
+ public int InvalidCount { get; private set; }
+
+ /// <summary>
+ /// Gets the count of skipped tests, excluding ignored tests
+ /// </summary>
+ public int SkipCount { get; private set; }
+
+ /// <summary>
+ /// Gets the ignore count
+ /// </summary>
+ public int IgnoreCount { get; private set; }
+
+ /// <summary>
+ /// Gets the explicit count
+ /// </summary>
+ public int ExplicitCount { get; private set; }
+
+ /// <summary>
+ /// Invalid Test Fixtures
+ /// </summary>
+ public int InvalidTestFixtures { get; private set; }
+
+ /// <summary>
+ /// Gets the ResultState of the test result, which
+ /// indicates the success or failure of the test.
+ /// </summary>
+ public ResultState ResultState { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the time the test started running.
+ /// </summary>
+ public DateTime StartTime { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the time the test finished running.
+ /// </summary>
+ public DateTime EndTime { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the elapsed time for running the test in seconds
+ /// </summary>
+ public double Duration { get; private set; }
+
+ #endregion
+
+ #region Helper Methods
+
+ private void InitializeCounters()
+ {
+ TestCount = 0;
+ PassCount = 0;
+ FailureCount = 0;
+ ErrorCount = 0;
+ InconclusiveCount = 0;
+ SkipCount = 0;
+ IgnoreCount = 0;
+ ExplicitCount = 0;
+ InvalidCount = 0;
+ }
+
+ private void Summarize(ITestResult result)
+ {
+ var label = result.ResultState.Label;
+ var status = result.ResultState.Status;
+
+ if (result.Test.IsSuite)
+ {
+ if (status == TestStatus.Failed && label == "Invalid")
+ InvalidTestFixtures++;
+
+ foreach (ITestResult r in result.Children)
+ Summarize(r);
+ }
+ else
+ {
+ TestCount++;
+ switch (status)
+ {
+ case TestStatus.Passed:
+ PassCount++;
+ break;
+ case TestStatus.Skipped:
+ if (label == "Ignored")
+ IgnoreCount++;
+ else if (label == "Explicit")
+ ExplicitCount++;
+ else
+ SkipCount++;
+ break;
+ case TestStatus.Failed:
+ if (label == "Invalid")
+ InvalidCount++;
+ else if (label == "Error")
+ ErrorCount++;
+ else
+ FailureCount++;
+ break;
+ case TestStatus.Inconclusive:
+ InconclusiveCount++;
+ break;
+ }
+
+ return;
+ }
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+// ****************************************************************************************************
+// Namespace: NUnitLite.TUnit
+// Class: TOutputManager
+// Description: Tizen Output Manager
+// Author: Nguyen Truong Duong <duong.nt1@samsung.com>
+// Notes:
+// Revision History:
+// Name: Date: Description:
+// ****************************************************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.IO;
+using NUnit.Common;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.TUnit;
+
+namespace NUnitLite.TUnit
+{
+ /// <summary>
+ /// TOutputManager is responsible for creating output files
+ /// from a test run in various formats.
+ /// </summary>
+ public class TOutputManager
+ {
+ private string _workDirectory;
+
+ /// <summary>
+ /// Construct an TOutputManager
+ /// </summary>
+ /// <param name="workDirectory">The directory to use for reports</param>
+ public TOutputManager(string workDirectory)
+ {
+ _workDirectory = workDirectory;
+ }
+
+ /// <summary>
+ /// Write the result of a test run according to a spec.
+ /// </summary>
+ /// <param name="result">The test result</param>
+ /// <param name="spec">An output specification</param>
+ /// <param name="runSettings">Settings</param>
+ /// <param name="filter">Filter</param>
+ public void WriteResultFile(ITestResult result, OutputSpecification spec, IDictionary<string, object> runSettings, TestFilter filter)
+ {
+ //string outputPath = Path.Combine(_workDirectory, spec.OutputPath);
+ // [DuongNT][BEGIN]: Get configured file path output
+ // Write results log
+ ResultSummary summary = new ResultSummary(result);
+ int totalTCT = summary.TestCount;
+ int passedTCT = summary.PassCount;
+ int failedTCT = summary.FailedCount;
+ int blockTCT = totalTCT - passedTCT - failedTCT;
+ TLogger.Write("");
+ TLogger.Write("#####Summary#####");
+ TLogger.Write("##### Total #####");
+ TLogger.Write("##### " + totalTCT + " #####");
+ TLogger.Write("##### PASS #####");
+ TLogger.Write("##### " + passedTCT + " #####");
+ TLogger.Write("##### FAIL #####");
+ TLogger.Write("##### " + failedTCT + " #####");
+ TLogger.Write("##### BLOCK #####");
+ TLogger.Write("##### " + blockTCT + " #####");
+ TLogger.Write("##### Details #####");
+ TLogger.Write("");
+
+ string outputPath = TSettings.GetInstance().GetOutputFilePathName();
+ if (outputPath == "")
+ outputPath = Path.Combine(_workDirectory, spec.OutputPath);
+ TLogger.Write("Completed test-suite's execution!");
+ TLogger.Write("Writing results to: " + outputPath + "...");
+ // [DuongNT][END]: Get configured file path output
+
+ OutputWriter outputWriter = null;
+
+ switch (spec.Format)
+ {
+ case "nunit3":
+ outputWriter = new NUnit3XmlOutputWriter();
+ break;
+
+ case "nunit2":
+ outputWriter = new NUnit2XmlOutputWriter();
+ break;
+
+ //case "user":
+ // Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
+ // string dir = Path.GetDirectoryName(uri.LocalPath);
+ // outputWriter = new XmlTransformOutputWriter(Path.Combine(dir, spec.Transform));
+ // break;
+
+ default:
+ throw new ArgumentException(
+ string.Format("Invalid XML output format '{0}'", spec.Format),
+ "spec");
+ }
+
+ outputWriter.WriteResultFile(result, outputPath, runSettings, filter);
+ TLogger.Write("Results saved to: " + outputPath);
+ }
+
+ /// <summary>
+ /// Write out the result of exploring the tests
+ /// </summary>
+ /// <param name="test">The top-level test</param>
+ /// <param name="spec">An OutputSpecification</param>
+ public void WriteTestFile(ITest test, OutputSpecification spec)
+ {
+ string outputPath = Path.Combine(_workDirectory, spec.OutputPath);
+ OutputWriter outputWriter = null;
+
+ switch (spec.Format)
+ {
+ case "nunit3":
+ outputWriter = new NUnit3XmlOutputWriter();
+ break;
+
+ case "cases":
+ outputWriter = new TestCaseOutputWriter();
+ break;
+
+ //case "user":
+ // Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
+ // string dir = Path.GetDirectoryName(uri.LocalPath);
+ // outputWriter = new XmlTransformOutputWriter(Path.Combine(dir, spec.Transform));
+ // break;
+
+ default:
+ throw new ArgumentException(
+ string.Format("Invalid XML output format '{0}'", spec.Format),
+ "spec");
+ }
+
+ outputWriter.WriteTestFile(test, outputPath);
+ Console.WriteLine("Tests ({0}) saved as {1}", spec.Format, outputPath);
+ }
+ }
+}
--- /dev/null
+// ****************************************************************************************************
+// Namespace: NUnitLite.TUnit
+// Class: TRunner
+// Description: Tizen UnitTest Runner to run Tizen C# test-suite automatically
+// Author: Nguyen Truong Duong <duong.nt1@samsung.com>
+// Notes:
+// Revision History:
+// Name: Date: Description:
+// ****************************************************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.IO;
+using System.Reflection;
+using System.Xml;
+using System.Threading;
+using System.Threading.Tasks;
+using NUnit.Framework.TUnit;
+using NUnit.Framework.Interfaces;
+using System.Collections.Generic;
+using System.ComponentModel;
+
+namespace NUnitLite.TUnit
+{
+ public class TRunner
+ {
+ private Assembly _testAssembly;
+ private TextRunner _textRunner;
+ private string[] args;
+ public static string TESTCASE_XML_NAME = "test";
+ private string pkgName = "";
+
+#if TIZEN
+ /**
+ * @summary: Declares event will be emitted when a single test execution done.
+ */
+ public event EventHandler<SingleTestDoneEventArgs> SingleTestDone;
+
+ /**
+ * @summary: Forwards event when a single test execution done.
+ */
+ protected virtual void OnSingleTestDone(SingleTestDoneEventArgs e)
+ {
+ EventHandler<SingleTestDoneEventArgs> handler = SingleTestDone;
+ if (handler != null)
+ {
+ handler(this, e);
+ }
+ }
+#endif
+
+ public TRunner(Assembly testAssembly)
+ {
+ _testAssembly = testAssembly;
+ Tizen.Log.Fatal("NUITEST", $"");
+ Tizen.Log.Fatal("NUITEST", $"TRunner() _testAssembly={_testAssembly}");
+#if TIZEN
+ TSettings.GetInstance().ConnectTestkitStub();
+#endif
+ }
+
+ public TRunner() : this(Assembly.GetEntryAssembly())
+ {
+ Tizen.Log.Fatal("NUITEST", $"");
+ Tizen.Log.Fatal("NUITEST", $"TRunner()");
+ }
+
+ /// <summary>
+ /// Get the app name of the Tizen package
+ /// </summary>
+ private string GetPackageName(string basePath)
+ {
+ // basePath = "/opt/home/owner/apps_rw/Tizen.Applications.Manual.Tests/bin/";
+ if (basePath.Contains("bin\\Debug"))
+ {
+ // If build on Window, return "Test"
+ //LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, "Run on Window");
+ return "Test";
+ }
+
+ string[] delimiter = { "/" };
+ string[] delimiterDot = { "." };
+ string[] strAry;
+ string returnValue = "";
+ try
+ {
+ strAry = basePath.Split(delimiter, StringSplitOptions.None);
+ foreach (string str in strAry)
+ {
+ if (str.Contains("Tizen."))
+ {
+ returnValue = str.Substring(6, str.Length - 12); //remove Tizen. and .Tests
+ // LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, "check : "+ returnValue);
+ break;
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ TLogger.WriteError(e.Message + e.ToString() + ". Please edit packageId as per guideline");
+ }
+
+ return returnValue;
+ }
+
+ /// <summary>
+ /// Execute the test suite automatically on the Tizen devidce
+ /// </summary>
+ public void LoadTestsuite()
+ {
+ Tizen.Log.Fatal("NUITEST", $"");
+ Tizen.Log.Fatal("NUITEST", $"LoadTestsuite()");
+ TSettings.CurTCIndex = 0;
+ string cache_path = Tizen.Applications.Application.Current.DirectoryInfo.Resource;
+ string dllPath = cache_path.Replace("res", "bin");//Cache->res
+ string pkgName = GetPackageName(dllPath);
+ if (pkgName == "")
+ {
+ Tizen.Log.Fatal("NUITEST", $"The package name is invalid!");
+ TLogger.WriteError("The package name is invalid!");
+ return;
+ }
+
+ //TLogger.Write("Executing the application: " + pkgName + "...");
+ Tizen.Log.Fatal("NUITEST", $"Executing the application: {pkgName}");
+ string exeFilePathName = "";
+ if(dllPath.Contains("netcoreapp"))
+ {
+ exeFilePathName = string.Format(dllPath + "Tizen.{0}Tests.dll", pkgName);
+ }
+ else
+ {
+ exeFilePathName = string.Format(dllPath + "Debug/netcoreapp3.1/Tizen.{0}dll", pkgName);
+ }
+ //TLogger.Write("exeFilePathName : " + exeFilePathName);
+ Tizen.Log.Fatal("NUITEST", $"exeFilePathName : {exeFilePathName}");
+
+ AssemblyName asmName = new AssemblyName(GetAssemblyName(exeFilePathName));
+ _testAssembly = Assembly.LoadFrom(exeFilePathName);
+
+ string pkgShareDir = $"{dllPath}{pkgName}";
+ System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(pkgShareDir);
+ if (di.Exists == false)
+ {
+ di.Create();
+ }
+
+ string outputFilePathName = string.Format("{0}/{1}.xml", pkgShareDir, TESTCASE_XML_NAME);
+
+ TSettings.GetInstance().SetOutputFilePathName(outputFilePathName);
+ string[] s = new string[1] { exeFilePathName };
+
+ Tizen.Log.Fatal("NUITEST", $"outputFilePathName : {outputFilePathName}");
+
+ //new TextRunner(_testAssembly).Execute(s);
+ LoadTestsuite(s, outputFilePathName);
+ }
+
+ /// <summary>
+ /// Execute the test suite automatically on the Tizen devidce
+ /// </summary>
+ public void LoadTestsuite(string dllPath, string pkgName)
+ {
+ TSettings.CurTCIndex = 0;
+ if (pkgName == "")
+ {
+ TLogger.Write("The package name is invalid!");
+ return;
+ }
+ TLogger.Write("Executing the application: " + pkgName + "...");
+
+
+ string exeFilePathName = string.Format(dllPath + "Tizen.{0}.Tests.exe", pkgName);
+
+ AssemblyName asmName = new AssemblyName(GetAssemblyName(exeFilePathName));
+ _testAssembly = Assembly.Load(asmName);
+
+ string pkgShareDir = string.Format("/home/owner/share/{0}", pkgName);
+ System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(pkgShareDir);
+ if (di.Exists == false)
+ {
+ di.Create();
+ }
+
+ string outputFilePathName = string.Format("{0}/{1}.xml", pkgShareDir, TESTCASE_XML_NAME);
+ TSettings.GetInstance().SetOutputFilePathName(outputFilePathName);
+ string[] s = new string[1] { exeFilePathName };
+ //new TextRunner(_testAssembly).Execute(s);
+ LoadTestsuite(s, outputFilePathName);
+ }
+
+ /// <summary>
+ /// Execute the tests in the assembly, passing in
+ /// a list of arguments.
+ /// </summary>
+ /// <param name="args">arguments for NUnitLite to use</param>
+ public void Execute()
+ {
+#if TIZEN
+ #region tronghieu.d - Create new thread to run test and mainthread waiting for invoke test method.
+ TAsyncThreadMgr asyncThreadMgr = TAsyncThreadMgr.GetInstance();
+ ManualResetEvent methodExecutionResetEvent = asyncThreadMgr.GetMethodExecutionResetEvent();
+ methodExecutionResetEvent.Reset();
+
+ Task t = Task.Run(() =>
+ {
+ _textRunner.Execute(args);
+ asyncThreadMgr.SetData(null, null, null, null, false);
+ methodExecutionResetEvent.Set();
+ });
+ t.GetAwaiter().OnCompleted(() =>
+ {
+ OnSingleTestDone(TSettings.GetInstance().GetSingleTestDoneEventArgs());
+ });
+ methodExecutionResetEvent.WaitOne();
+ asyncThreadMgr.RunTestMethod();
+ #endregion
+#else
+ new TextRunner(_testAssembly).Execute(args);
+#endif
+ }
+
+ private string GetAssemblyName(string assemblyFullPath)
+ {
+
+ string[] delimiter1 = { "\\" };
+ string[] delimiter2 = { "/" };
+ string[] delimiterDot = { "." };
+ string[] delimiterExe = { ".exe" };
+ string[] strAry;
+ string returnValue = "";
+ try
+ {
+ strAry = assemblyFullPath.Split(delimiter1, StringSplitOptions.None);
+
+ if (strAry.Length < 2)
+ strAry = assemblyFullPath.Split(delimiter2, StringSplitOptions.None);
+
+ foreach (string str in strAry)
+ {
+ if (str.Contains(".Tests.dll"))
+ {
+ string[] strSplit = str.Split(delimiterDot, StringSplitOptions.None);
+ returnValue = strSplit[0];
+ //LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, "check : "+ returnValue);
+ break;
+ }
+ if (str.Contains(".exe"))
+ {
+ string[] strSplit = str.Split(delimiterExe, StringSplitOptions.None);
+ returnValue = strSplit[0];
+ break;
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ TLogger.WriteError(TLogger.ExceptionTag , e.Message + e.ToString() + ". Please edit packageId as per guideline");
+ }
+
+ return returnValue;
+ }
+
+ public void LoadTestsuite(string[] args, string tcListPath = "")
+ {
+ this.args = args;
+ _textRunner = new TextRunner(_testAssembly);
+#if TIZEN
+ _textRunner.LoadTest(args);
+ //WriteTestList(tcListPath);
+#endif
+ }
+#if TIZEN
+ public Dictionary<string, ITest> GetTestList()
+ {
+ return _textRunner.TestcaseList;
+ }
+
+ public void WriteTestList(string path)
+ {
+ LogUtils.Write(LogUtils.INFO, LogUtils.TAG, "In WriteTestList");
+ XMLUtils xmlUtils = new XMLUtils();
+ TestcaseEnvironment testEnv = new TestcaseEnvironment();
+ testEnv.build_id = "test";
+ testEnv.device_id = "csharp_device";
+ testEnv.device_model = "";
+ testEnv.device_name = "N/A";
+ testEnv.host = "N/A";
+ testEnv.resolution = "N/A";
+
+ List<TestcaseData> tcList = new List<TestcaseData>();
+
+ foreach (KeyValuePair<string, ITest> pair in _textRunner.TestcaseList)
+ {
+ TestcaseData testData = new TestcaseData();
+ testData.id = pair.Key;
+ if (pkgName.Contains("manual"))
+ testData.execution_type = "manual";
+ else
+ testData.execution_type = "auto";
+ tcList.Add(testData);
+ }
+
+ try
+ {
+ xmlUtils.writeResult("", path, testEnv, tcList);
+ }
+ catch (Exception e)
+ {
+ TLogger.WriteError(TLogger.ExceptionTag, e.Message + e.ToString());
+ LogUtils.Write(LogUtils.ERROR, LogUtils.TAG, e.Message + e.ToString());
+ }
+ }
+
+#endif
+ }
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2014 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#if !SILVERLIGHT && !NETCF
+using System;
+using System.Globalization;
+using System.IO;
+using NUnit.Framework.Interfaces;
+
+namespace NUnitLite
+{
+ /// <summary>
+ /// TeamCityEventListener class handles ITestListener events
+ /// by issuing TeamCity service messages on the Console.
+ /// </summary>
+ public class TeamCityEventListener : ITestListener
+ {
+ readonly TextWriter _outWriter;
+
+ /// <summary>
+ /// Default constructor using Console.Out
+ /// </summary>
+ /// <remarks>
+ /// This constructor must be called before Console.Out is
+ /// redirected in order to work correctly under TeamCity.
+ /// </remarks>
+ public TeamCityEventListener() : this(Console.Out) { }
+
+ /// <summary>
+ /// Construct a TeamCityEventListener specifying a TextWriter. Used for testing.
+ /// </summary>
+ /// <param name="outWriter">The TextWriter to receive normal messages.</param>
+ public TeamCityEventListener(TextWriter outWriter)
+ {
+ _outWriter = outWriter;
+ }
+
+ /// <summary>
+ /// Called when a test has just started
+ /// </summary>
+ /// <param name="test">The test that is starting</param>
+ public void TestStarted(ITest test)
+ {
+ if (test.IsSuite)
+ TC_TestSuiteStarted(test.Name);
+ else
+ TC_TestStarted(test.Name);
+ }
+
+ /// <summary>
+ /// Called when a test has finished
+ /// </summary>
+ /// <param name="result">The result of the test</param>
+ public void TestFinished(ITestResult result)
+ {
+ string testName = result.Test.Name;
+
+ if (result.Test.IsSuite)
+ TC_TestSuiteFinished(testName);
+ else
+ switch (result.ResultState.Status)
+ {
+ case TestStatus.Passed:
+ TC_TestFinished(testName, result.Duration);
+ break;
+ case TestStatus.Inconclusive:
+ TC_TestIgnored(testName, "Inconclusive");
+ break;
+ case TestStatus.Skipped:
+ TC_TestIgnored(testName, result.Message);
+ break;
+ case TestStatus.Failed:
+ TC_TestFailed(testName, result.Message, result.StackTrace);
+ TC_TestFinished(testName, result.Duration);
+ break;
+ }
+ }
+
+ /// <summary>
+ /// Called when a test produces output for immediate display
+ /// </summary>
+ /// <param name="output">A TestOutput object containing the text to display</param>
+ public void TestOutput(TestOutput output) { }
+
+ #region Helper Methods
+
+ private void TC_TestSuiteStarted(string name)
+ {
+ _outWriter.WriteLine("##teamcity[testSuiteStarted name='{0}']", Escape(name));
+ }
+
+ private void TC_TestSuiteFinished(string name)
+ {
+ _outWriter.WriteLine("##teamcity[testSuiteFinished name='{0}']", Escape(name));
+ }
+
+ private void TC_TestStarted(string name)
+ {
+ _outWriter.WriteLine("##teamcity[testStarted name='{0}' captureStandardOutput='true']", Escape(name));
+ }
+
+ private void TC_TestFinished(string name, double duration)
+ {
+ // TeamCity expects the duration to be in milliseconds
+ int milliseconds = (int)(duration * 1000d);
+ _outWriter.WriteLine("##teamcity[testFinished name='{0}' duration='{1}']", Escape(name), milliseconds);
+ }
+
+ private void TC_TestIgnored(string name, string reason)
+ {
+ _outWriter.WriteLine("##teamcity[testIgnored name='{0}' message='{1}']", Escape(name), Escape(reason));
+ }
+
+ private void TC_TestFailed(string name, string message, string details)
+ {
+ _outWriter.WriteLine("##teamcity[testFailed name='{0}' message='{1}' details='{2}']", Escape(name), Escape(message), Escape(details));
+ }
+
+ private static string Escape(string input)
+ {
+ return input != null
+ ? input.Replace("|", "||")
+ .Replace("'", "|'")
+ .Replace("\n", "|n")
+ .Replace("\r", "|r")
+ .Replace(char.ConvertFromUtf32(int.Parse("0086", NumberStyles.HexNumber)), "|x")
+ .Replace(char.ConvertFromUtf32(int.Parse("2028", NumberStyles.HexNumber)), "|l")
+ .Replace(char.ConvertFromUtf32(int.Parse("2029", NumberStyles.HexNumber)), "|p")
+ .Replace("[", "|[")
+ .Replace("]", "|]")
+ : null;
+ }
+
+ #endregion
+ }
+}
+#endif
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+#define TIZEN
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Reflection;
+using NUnit.Common;
+using NUnit.Framework.Api;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.Internal.Filters;
+#if TIZEN
+using NUnitLite.TUnit;
+using NUnit.Framework.TUnit;
+#endif
+
+namespace NUnitLite
+{
+ /// <summary>
+ /// TextRunner is a general purpose class that runs tests and
+ /// outputs to a text-based user interface (TextUI).
+ ///
+ /// Call it from your Main like this:
+ /// new TextRunner(textWriter).Execute(args);
+ /// OR
+ /// new TextUI().Execute(args);
+ /// The provided TextWriter is used by default, unless the
+ /// arguments to Execute override it using -out. The second
+ /// form uses the Console, provided it exists on the platform.
+ ///
+ /// NOTE: When running on a platform without a Console, such
+ /// as Windows Phone, the results will simply not appear if
+ /// you fail to specify a file in the call itself or as an option.
+ /// </summary>
+ public class TextRunner : ITestListener
+ {
+ #region Runner Return Codes
+
+ /// <summary>OK</summary>
+ public const int OK = 0;
+ /// <summary>Invalid Arguments</summary>
+ public const int INVALID_ARG = -1;
+ /// <summary>File not found</summary>
+ public const int FILE_NOT_FOUND = -2;
+ /// <summary>Test fixture not found - No longer in use</summary>
+ //public const int FIXTURE_NOT_FOUND = -3;
+ /// <summary>Invalid test suite</summary>
+ public const int INVALID_TEST_FIXTURE = -4;
+ /// <summary>Unexpected error occurred</summary>
+ public const int UNEXPECTED_ERROR = -100;
+
+ #endregion
+
+ private Assembly _testAssembly;
+ private readonly List<Assembly> _assemblies = new List<Assembly>();
+ private ITestAssemblyRunner _runner;
+
+ private NUnitLiteOptions _options;
+ private ITestListener _teamCity = null;
+
+ private TextUI _textUI;
+
+
+ #region Constructors
+
+ //// <summary>
+ //// Initializes a new instance of the <see cref="TextRunner"/> class.
+ //// </summary>
+ public TextRunner() { }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TextRunner"/> class
+ /// specifying a test assembly whose tests are to be run.
+ /// </summary>
+ /// <param name="testAssembly"></param>
+ /// </summary>
+ public TextRunner(Assembly testAssembly)
+ {
+ _testAssembly = testAssembly;
+ }
+
+ #endregion
+
+ #region Properties
+
+ public ResultSummary Summary { get; private set; }
+
+ #endregion
+
+ #region Public Methods
+ #if TIZEN
+ public Dictionary<string, ITest> TestcaseList
+ {
+ get { return _runner.GetTestcaseIDList(); }
+ }
+
+ public void LoadTest(string[] args)
+ {
+ //TLogger.Write("LoadTest ..................");
+ _options = new NUnitLiteOptions(args);
+ ExtendedTextWriter outWriter = null;
+ outWriter = new ColorConsoleWriter();
+ _textUI = new TextUI(outWriter, Console.In, _options);
+ _runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder());
+ try
+ {
+ #if !SILVERLIGHT && !PORTABLE
+ if (!Directory.Exists(_options.WorkDirectory))
+ Directory.CreateDirectory(_options.WorkDirectory);
+
+ #if !NETCF
+ if (_options.TeamCity)
+ _teamCity = new TeamCityEventListener();
+ #endif
+ #endif
+
+ if (_options.ShowVersion || !_options.NoHeader)
+ _textUI.DisplayHeader();
+
+ if (_options.ShowHelp)
+ {
+ _textUI.DisplayHelp();
+ return;
+ }
+
+ // We already showed version as a part of the header
+ if (_options.ShowVersion)
+ return;
+
+ if (_options.ErrorMessages.Count > 0)
+ {
+ _textUI.DisplayErrors(_options.ErrorMessages);
+ _textUI.DisplayHelp();
+
+ return;
+ }
+
+ _textUI.DisplayRuntimeEnvironment();
+
+ var testFile = _testAssembly != null
+ ? AssemblyHelper.GetAssemblyPath(_testAssembly)
+ : _options.InputFiles.Count > 0
+ ? _options.InputFiles[0]
+ : null;
+
+ //TLogger.Write("Input File [0]:" + _options.InputFiles[0]);
+ //TLogger.Write("Input File Format Size :"+ _options.InputFiles.Count);
+
+ if (testFile != null)
+ {
+ _textUI.DisplayTestFiles(new string[] { testFile });
+ //TLogger.Write("after DisplayTestFiles");
+ if (_testAssembly == null)
+ _testAssembly = AssemblyHelper.Load(testFile);
+ }
+
+
+ if (_options.WaitBeforeExit && _options.OutFile != null)
+ _textUI.DisplayWarning("Ignoring /wait option - only valid for Console");
+
+ foreach (string nameOrPath in _options.InputFiles) {
+ //TLogger.Write("In foreach" + nameOrPath);
+ _assemblies.Add(AssemblyHelper.Load(nameOrPath));
+ }
+
+ // We display the filters at this point so that any exception message
+ // thrown by CreateTestFilter will be understandable.
+ _textUI.DisplayTestFilters();
+ var runSettings = MakeRunSettings(_options);
+
+ TestFilter filter = CreateTestFilter(_options);
+
+ _runner.Load(_testAssembly, runSettings);
+ }
+ catch (FileNotFoundException ex)
+ {
+ _textUI.DisplayError(ex.Message);
+ return;
+ }
+ catch (Exception ex)
+ {
+ _textUI.DisplayError(ex.ToString());
+ return;
+ }
+ #if !SILVERLIGHT
+ finally
+ {
+ if (_options.WaitBeforeExit)
+ _textUI.WaitForUser("Press Enter key to continue . . .");
+ if (_options.OutFile != null && outWriter != null)
+ outWriter.Flush();
+ }
+ #endif
+ }
+ #endif
+
+ #if !SILVERLIGHT && !PORTABLE
+ public int Execute(string[] args)
+ {
+ var options = new NUnitLiteOptions(args);
+
+ InitializeInternalTrace(options);
+
+ ExtendedTextWriter outWriter = null;
+ if (options.OutFile != null)
+ {
+ outWriter = new ExtendedTextWrapper(TextWriter.Synchronized(new StreamWriter(Path.Combine(options.WorkDirectory, options.OutFile))));
+ Console.SetOut(outWriter);
+ }
+ else
+ {
+ outWriter = new ColorConsoleWriter();
+ }
+
+ TextWriter errWriter = null;
+ if (options.ErrFile != null)
+ {
+ errWriter = TextWriter.Synchronized(new StreamWriter(Path.Combine(options.WorkDirectory, options.ErrFile)));
+ Console.SetError(errWriter);
+ }
+
+ try
+ {
+ return Execute(outWriter, Console.In, options);
+ }
+ finally
+ {
+ if (options.OutFile != null && outWriter != null)
+ outWriter.Close();
+
+ if (options.ErrFile != null && errWriter != null)
+ errWriter.Close();
+ }
+ }
+ #else
+ public int Execute(string[] args)
+ {
+ var options = new NUnitLiteOptions(args);
+ ExtendedTextWriter outWriter = null;
+ outWriter = new ColorConsoleWriter();
+ try
+ {
+ return Execute(outWriter, Console.In, options);
+ }
+ finally
+ {
+ if (options.OutFile != null && outWriter != null)
+ outWriter.Flush();
+ }
+ }
+ #endif
+
+ public int Execute(ExtendedTextWriter writer, TextReader reader, NUnitLiteOptions options)
+ {
+ var textUI = new TextUI(writer, reader, options);
+ return Execute(textUI, options);
+ }
+
+ /// <summary>
+ /// Execute a test run
+ /// </summary>
+ /// <param name="callingAssembly">The assembly from which tests are loaded</param>
+ public int Execute(TextUI textUI, NUnitLiteOptions options)
+ {
+ _textUI = textUI;
+ _options = options;
+ if (_runner == null)
+ _runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder());
+
+ try
+ {
+#if !TIZEN
+#if !SILVERLIGHT && !PORTABLE
+ if (!Directory.Exists(_options.WorkDirectory))
+ Directory.CreateDirectory(_options.WorkDirectory);
+
+#if !NETCF
+ if (_options.TeamCity)
+ _teamCity = new TeamCityEventListener();
+#endif
+#endif
+
+ if (_options.ShowVersion || !_options.NoHeader)
+ _textUI.DisplayHeader();
+
+ if (_options.ShowHelp)
+ {
+ _textUI.DisplayHelp();
+ return TextRunner.OK;
+ }
+
+ // We already showed version as a part of the header
+ if (_options.ShowVersion)
+ return TextRunner.OK;
+
+ if (_options.ErrorMessages.Count > 0)
+ {
+ _textUI.DisplayErrors(_options.ErrorMessages);
+ _textUI.DisplayHelp();
+
+ return TextRunner.INVALID_ARG;
+ }
+
+ _textUI.DisplayRuntimeEnvironment();
+
+ var testFile = _testAssembly != null
+ ? AssemblyHelper.GetAssemblyPath(_testAssembly)
+ : _options.InputFiles.Count > 0
+ ? _options.InputFiles[0]
+ : null;
+
+ if (testFile != null)
+ {
+ _textUI.DisplayTestFiles(new string[] { testFile });
+ if (_testAssembly == null)
+ _testAssembly = AssemblyHelper.Load(testFile);
+ }
+
+
+ if (_options.WaitBeforeExit && _options.OutFile != null)
+ _textUI.DisplayWarning("Ignoring /wait option - only valid for Console");
+
+ foreach (string nameOrPath in _options.InputFiles){
+ _assemblies.Add(AssemblyHelper.Load(nameOrPath));
+ }
+
+ // We display the filters at this point so that any exception message
+ // thrown by CreateTestFilter will be understandable.
+ _textUI.DisplayTestFilters();
+#endif
+ var runSettings = MakeRunSettings(_options);
+
+ TestFilter filter = CreateTestFilter(_options);
+
+ //_runner.Load(_testAssembly, runSettings);
+
+ return _options.Explore ? ExploreTests() : RunTests(filter, runSettings);
+ }
+ catch (FileNotFoundException ex)
+ {
+ _textUI.DisplayError(ex.Message);
+ return FILE_NOT_FOUND;
+ }
+ catch (Exception ex)
+ {
+ _textUI.DisplayError(ex.ToString());
+ return UNEXPECTED_ERROR;
+ }
+ #if !SILVERLIGHT
+ finally
+ {
+ if (_options.WaitBeforeExit)
+ _textUI.WaitForUser("Press Enter key to continue . . .");
+ }
+ #endif
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ public int RunTests(TestFilter filter, IDictionary<string, object> runSettings)
+ {
+ var startTime = DateTime.UtcNow;
+
+ ITestResult result = _runner.Run(this, filter);
+
+ #if SILVERLIGHT
+ // Silverlight can't display results while the test is running
+ // so we do it afterwards.
+ foreach(ITestResult testResult in _results)
+ _textUI.TestFinished(testResult);
+ #endif
+ ReportResults(result);
+
+ #if !SILVERLIGHT && !PORTABLE
+ if (_options.ResultOutputSpecifications.Count > 0)
+ {
+ #if TIZEN
+ // [DuongNT]: Create Tizen OutputManager
+ var outputManager = new TOutputManager(_options.WorkDirectory);
+ #else
+ var outputManager = new OutputManager(_options.WorkDirectory);
+ #endif
+ foreach (var spec in _options.ResultOutputSpecifications)
+ outputManager.WriteResultFile(result, spec, runSettings, filter);
+ }
+ #endif
+ if (Summary.InvalidTestFixtures > 0)
+ return INVALID_TEST_FIXTURE;
+
+ return Summary.FailureCount + Summary.ErrorCount + Summary.InvalidCount;
+ }
+
+ public void ReportResults(ITestResult result)
+ {
+ Summary = new ResultSummary(result);
+
+ if (Summary.ExplicitCount + Summary.SkipCount + Summary.IgnoreCount > 0)
+ _textUI.DisplayNotRunReport(result);
+
+ if (result.ResultState.Status == TestStatus.Failed)
+ _textUI.DisplayErrorsAndFailuresReport(result);
+
+ #if FULL
+ if (_options.Full)
+ _textUI.PrintFullReport(_result);
+ #endif
+ if (TSettings.GetInstance().IsManual == false)
+ {
+ _textUI.DisplayRunSettings();
+
+ _textUI.DisplaySummaryReport(Summary);
+ }
+ }
+
+ private int ExploreTests()
+ {
+ #if !PORTABLE && !SILVERLIGHT
+ ITest testNode = _runner.LoadedTest;
+
+ var specs = _options.ExploreOutputSpecifications;
+
+ if (specs.Count == 0)
+ new TestCaseOutputWriter().WriteTestFile(testNode, Console.Out);
+ else
+ {
+ var outputManager = new OutputManager(_options.WorkDirectory);
+
+ foreach (var spec in _options.ExploreOutputSpecifications)
+ outputManager.WriteTestFile(testNode, spec);
+ }
+ #endif
+
+ return OK;
+ }
+
+ /// <summary>
+ /// Make the settings for this run - this is public for testing
+ /// </summary>
+ public static Dictionary<string, object> MakeRunSettings(NUnitLiteOptions options)
+ {
+ // Transfer command line options to run settings
+ var runSettings = new Dictionary<string, object>();
+
+ if (options.RandomSeed >= 0)
+ runSettings[PackageSettings.RandomSeed] = options.RandomSeed;
+
+ #if !PORTABLE
+ if (options.WorkDirectory != null)
+ runSettings[PackageSettings.WorkDirectory] = Path.GetFullPath(options.WorkDirectory);
+ #endif
+ if (options.DefaultTimeout >= 0)
+ runSettings[PackageSettings.DefaultTimeout] = options.DefaultTimeout;
+
+ if (options.StopOnError)
+ runSettings[PackageSettings.StopOnError] = true;
+
+ if (options.DefaultTestNamePattern != null)
+ runSettings[PackageSettings.DefaultTestNamePattern] = options.DefaultTestNamePattern;
+
+ return runSettings;
+ }
+
+ /// <summary>
+ /// Create the test filter for this run - public for testing
+ /// </summary>
+ /// <param name="options"></param>
+ /// <returns></returns>
+ public static TestFilter CreateTestFilter(NUnitLiteOptions options)
+ {
+ var filter = TestFilter.Empty;
+
+ if (options.TestList.Count > 0)
+ {
+ var testFilters = new List<TestFilter>();
+ foreach (var test in options.TestList)
+ testFilters.Add(new FullNameFilter(test));
+
+ filter = testFilters.Count > 1
+ ? new OrFilter(testFilters.ToArray())
+ : testFilters[0];
+ }
+
+
+ if (options.WhereClauseSpecified)
+ {
+ string xmlText = new TestSelectionParser().Parse(options.WhereClause);
+ var whereFilter = TestFilter.FromXml(TNode.FromXml(xmlText));
+ filter = filter.IsEmpty
+ ? whereFilter
+ : new AndFilter(filter, whereFilter);
+ }
+
+ return filter;
+ }
+
+ #if !PORTABLE && !SILVERLIGHT
+ private void InitializeInternalTrace(NUnitLiteOptions _options)
+ {
+ var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), _options.InternalTraceLevel ?? "Off", true);
+
+ if (traceLevel != InternalTraceLevel.Off)
+ {
+ var logName = GetLogFileName();
+
+ #if NETCF // NETCF: Try to encapsulate this
+ InternalTrace.Initialize(Path.Combine(NUnit.Env.DocumentFolder, logName), traceLevel);
+ #else
+ StreamWriter streamWriter = null;
+ if (traceLevel > InternalTraceLevel.Off)
+ {
+ string logPath = Path.Combine(Environment.CurrentDirectory, logName);
+ streamWriter = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.Write));
+ streamWriter.AutoFlush = true;
+ }
+ InternalTrace.Initialize(streamWriter, traceLevel);
+ #endif
+}
+}
+
+private string GetLogFileName()
+{
+ const string LOG_FILE_FORMAT = "InternalTrace.{0}.{1}.{2}";
+
+ // Some mobiles don't have an Open With menu item,
+ // so we use .txt, which is opened easily.
+ #if NETCF
+ const string ext = "txt";
+ #else
+ const string ext = "log";
+ #endif
+ var baseName = _testAssembly != null
+ ? _testAssembly.GetName().Name
+ : _options.InputFiles.Count > 0
+ ? Path.GetFileNameWithoutExtension(_options.InputFiles[0])
+ : "NUnitLite";
+
+ return string.Format(LOG_FILE_FORMAT, Process.GetCurrentProcess().Id, baseName, ext);
+}
+ #endif
+
+#endregion
+
+#region ITestListener Members
+
+/// <summary>
+/// Called when a test or suite has just started
+/// </summary>
+/// <param name="test">The test that is starting</param>
+public void TestStarted(ITest test)
+{
+ if (_teamCity != null)
+ _teamCity.TestStarted(test);
+}
+
+/// <summary>
+/// Called when a test has finished
+/// </summary>
+/// <param name="result">The result of the test</param>
+public void TestFinished(ITestResult result)
+{
+ if (_teamCity != null)
+ _teamCity.TestFinished(result);
+
+ #if !SILVERLIGHT
+ _textUI.TestFinished(result);
+ #else
+ // For Silverlight, we can't display the results
+ // until the run is completed. We don't save anything
+ // unless there is associated output, since that's
+ // the only time we display anything in Silverlight.
+ if (result.Output.Length > 0)
+ _results.Add(result);
+ #endif
+}
+
+/// <summary>
+/// Called when a test produces output for immediate display
+/// </summary>
+/// <param name="output">A TestOutput object containing the text to display</param>
+public void TestOutput(TestOutput output)
+{
+ _textUI.TestOutput(output);
+}
+
+#endregion
+}
+}
--- /dev/null
+// ***********************************************************************
+// Copyright (c) 2015 Charlie Poole
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// ***********************************************************************
+#define PORTABLE
+#define TIZEN
+#define NUNIT_FRAMEWORK
+#define NUNITLITE
+#define NET_4_5
+#define PARALLEL
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Reflection;
+using NUnit.Common;
+using NUnit.Compatibility;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.TUnit;
+
+namespace NUnitLite
+{
+ public class TextUI
+ {
+ private ExtendedTextWriter _writer;
+ private TextReader _reader;
+ private NUnitLiteOptions _options;
+
+ #region Constructors
+
+ public TextUI(ExtendedTextWriter writer, TextReader reader, NUnitLiteOptions options)
+ {
+ _options = options;
+ _writer = writer;
+ _reader = reader;
+ }
+
+ public TextUI(ExtendedTextWriter writer, TextReader reader)
+ : this(writer, reader, new NUnitLiteOptions()) { }
+
+ public TextUI(ExtendedTextWriter writer)
+#if SILVERLIGHT || PORTABLE
+ : this(writer, null, new NUnitLiteOptions()) { }
+#else
+ : this(writer, Console.In, new NUnitLiteOptions()) { }
+#endif
+
+ #endregion
+
+ #region Public Methods
+
+ #region DisplayHeader
+
+ /// <summary>
+ /// Writes the header.
+ /// </summary>
+ public void DisplayHeader()
+ {
+ Assembly executingAssembly = GetType().GetTypeInfo().Assembly;
+ AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(executingAssembly);
+ Version version = assemblyName.Version;
+ string copyright = "Copyright (C) 2016, Charlie Poole";
+ string build = "";
+
+ var copyrightAttr = executingAssembly.GetCustomAttribute<AssemblyCopyrightAttribute>();
+ if (copyrightAttr != null)
+ copyright = copyrightAttr.Copyright;
+
+ var configAttr = executingAssembly.GetCustomAttribute<AssemblyConfigurationAttribute>();
+ if (configAttr != null)
+ build = string.Format("({0})", configAttr.Configuration);
+
+ WriteHeader(String.Format("NUnitLite {0} {1}", version.ToString(3), build));
+ WriteSubHeader(copyright);
+ _writer.WriteLine();
+ }
+
+ #endregion
+
+ #region DisplayTestFiles
+
+ public void DisplayTestFiles(IEnumerable<string> testFiles)
+ {
+ WriteSectionHeader("Test Files");
+
+ foreach (string testFile in testFiles)
+ _writer.WriteLine(ColorStyle.Default, " " + testFile);
+
+ _writer.WriteLine();
+ }
+
+ #endregion
+
+ #region DisplayHelp
+
+ public void DisplayHelp()
+ {
+ WriteHeader("Usage: NUNITLITE [assembly] [options]");
+ _writer.WriteLine();
+ WriteHelpLine("Runs a set of NUnitLite tests from the console.");
+ _writer.WriteLine();
+
+ WriteSectionHeader("Assembly:");
+ WriteHelpLine(" An alternate assembly from which to execute tests. Normally, the tests");
+ WriteHelpLine(" contained in the executable test assembly itself are run. An alternate");
+ WriteHelpLine(" assembly is specified using the assembly name, without any path or.");
+ WriteHelpLine(" extension. It must be in the same in the same directory as the executable");
+ WriteHelpLine(" or on the probing path.");
+ _writer.WriteLine();
+
+ WriteSectionHeader("Options:");
+ using (var sw = new StringWriter())
+ {
+ _options.WriteOptionDescriptions(sw);
+ _writer.Write(ColorStyle.Help, sw.ToString());
+ }
+
+ WriteSectionHeader("Notes:");
+ WriteHelpLine(" * File names may be listed by themselves, with a relative path or ");
+ WriteHelpLine(" using an absolute path. Any relative path is based on the current ");
+ WriteHelpLine(" directory or on the Documents folder if running on a under the ");
+ WriteHelpLine(" compact framework.");
+ _writer.WriteLine();
+ WriteHelpLine(" * On Windows, options may be prefixed by a '/' character if desired");
+ _writer.WriteLine();
+ WriteHelpLine(" * Options that take values may use an equal sign or a colon");
+ WriteHelpLine(" to separate the option from its value.");
+ _writer.WriteLine();
+ WriteHelpLine(" * Several options that specify processing of XML output take");
+ WriteHelpLine(" an output specification as a value. A SPEC may take one of");
+ WriteHelpLine(" the following forms:");
+ WriteHelpLine(" --OPTION:filename");
+ WriteHelpLine(" --OPTION:filename;format=formatname");
+ WriteHelpLine(" --OPTION:filename;transform=xsltfile");
+ _writer.WriteLine();
+ WriteHelpLine(" The --result option may use any of the following formats:");
+ WriteHelpLine(" nunit3 - the native XML format for NUnit 3.0");
+ WriteHelpLine(" nunit2 - legacy XML format used by earlier releases of NUnit");
+ _writer.WriteLine();
+ WriteHelpLine(" The --explore option may use any of the following formats:");
+ WriteHelpLine(" nunit3 - the native XML format for NUnit 3.0");
+ WriteHelpLine(" cases - a text file listing the full names of all test cases.");
+ WriteHelpLine(" If --explore is used without any specification following, a list of");
+ WriteHelpLine(" test cases is output to the console.");
+ _writer.WriteLine();
+ }
+
+ #endregion
+
+ #region DisplayRuntimeEnvironment
+
+ /// <summary>
+ /// Displays info about the runtime environment.
+ /// </summary>
+ public void DisplayRuntimeEnvironment()
+ {
+#if !PORTABLE
+ WriteSectionHeader("Runtime Environment");
+ _writer.WriteLabelLine(" OS Version: ", Environment.OSVersion);
+ _writer.WriteLabelLine(" CLR Version: ", Environment.Version);
+ _writer.WriteLine();
+#endif
+ }
+
+ #endregion
+
+ #region DisplayTestFilters
+
+ public void DisplayTestFilters()
+ {
+ if (_options.TestList.Count > 0 || _options.WhereClauseSpecified)
+ {
+ WriteSectionHeader("Test Filters");
+
+ if (_options.TestList.Count > 0)
+ foreach (string testName in _options.TestList)
+ _writer.WriteLabelLine(" Test: ", testName);
+
+ if (_options.WhereClauseSpecified)
+ _writer.WriteLabelLine(" Where: ", _options.WhereClause.Trim());
+
+ _writer.WriteLine();
+ }
+ }
+
+ #endregion
+
+ #region DisplayRunSettings
+
+ public void DisplayRunSettings()
+ {
+ WriteSectionHeader("Run Settings");
+
+ if (_options.DefaultTimeout >= 0)
+ _writer.WriteLabelLine(" Default timeout: ", _options.DefaultTimeout);
+
+#if PARALLEL
+ _writer.WriteLabelLine(
+ " Number of Test Workers: ",
+ _options.NumberOfTestWorkers >= 0
+ ? _options.NumberOfTestWorkers
+#if NETCF
+ : 2);
+#else
+ : Math.Max(Environment.ProcessorCount, 2));
+#endif
+#endif
+
+#if !PORTABLE
+ _writer.WriteLabelLine(" Work Directory: ", _options.WorkDirectory ?? NUnit.Env.DefaultWorkDirectory);
+#endif
+
+ _writer.WriteLabelLine(" Internal Trace: ", _options.InternalTraceLevel ?? "Off");
+
+ if (_options.TeamCity)
+ _writer.WriteLine(ColorStyle.Value, " Display TeamCity Service Messages");
+
+ _writer.WriteLine();
+ }
+
+ #endregion
+
+ #region TestFinished
+
+ private bool _testCreatedOutput = false;
+
+ public void TestFinished(ITestResult result)
+ {
+ bool isSuite = result.Test.IsSuite;
+
+ var labels = "ON";
+
+#if !SILVERLIGHT
+ if (_options.DisplayTestLabels != null)
+ labels = _options.DisplayTestLabels.ToUpperInvariant();
+#endif
+
+ if (!isSuite && labels == "ALL" || !isSuite && labels == "ON" && result.Output.Length > 0)
+ {
+ WriteLabelLine(result.Test.FullName);
+ }
+
+ if (result.Output.Length > 0)
+ {
+ WriteOutputLine(result.Output);
+
+ if (!result.Output.EndsWith("\n"))
+ _writer.WriteLine();
+ }
+
+ if (result.Test is TestAssembly && _testCreatedOutput)
+ {
+ _writer.WriteLine();
+ _testCreatedOutput = false;
+ }
+ }
+
+ #endregion
+
+ #region TestOutput
+
+ public void TestOutput(TestOutput output)
+ {
+ var labels = "ON";
+
+#if !SILVERLIGHT
+ if (_options.DisplayTestLabels != null)
+ labels = _options.DisplayTestLabels.ToUpperInvariant();
+#endif
+
+ if (labels == "ON" || labels == "All")
+ if (output.TestName != null)
+ WriteLabelLine(output.TestName);
+
+ WriteOutputLine(output.Stream == "Error" ? ColorStyle.Error : ColorStyle.Output, output.Text);
+ }
+
+ #endregion
+
+ #region WaitForUser
+
+ public void WaitForUser(string message)
+ {
+ // Ignore if we don't have a TextReader
+ if (_reader != null)
+ {
+ _writer.WriteLine(ColorStyle.Label, message);
+ _reader.ReadLine();
+ }
+ }
+
+ #endregion
+
+ #region Test Result Reports
+
+ #region DisplaySummaryReport
+
+ public void DisplaySummaryReport(ResultSummary summary)
+ {
+ var status = summary.ResultState.Status;
+
+ var overallResult = status.ToString();
+ if (overallResult == "Skipped")
+ overallResult = "Warning";
+
+ ColorStyle overallStyle = status == TestStatus.Passed
+ ? ColorStyle.Pass
+ : status == TestStatus.Failed
+ ? ColorStyle.Failure
+ : status == TestStatus.Skipped
+ ? ColorStyle.Warning
+ : ColorStyle.Output;
+
+ if (_testCreatedOutput)
+ _writer.WriteLine();
+ WriteSectionHeader(" ");
+ WriteSectionHeader("######################################################################################");
+ WriteSectionHeader("################################### TEST RUN SUMMARY #################################");
+ _writer.WriteLabelLine(TLogger.DefaultTag + "############ Overall result: ", overallResult, overallStyle);
+
+ WriteSummaryCount(TLogger.DefaultTag + "############ Test Count: ", summary.TestCount);
+ WriteSummaryCount(", Passed: ", summary.PassCount);
+ WriteSummaryCount(", Failed: ", summary.FailedCount, ColorStyle.Failure);
+ WriteSummaryCount(", Inconclusive: ", summary.InconclusiveCount);
+ WriteSummaryCount(", Skipped: ", summary.TotalSkipCount);
+ _writer.WriteLine();
+
+ if (summary.FailedCount > 0)
+ {
+ WriteSummaryCount(TLogger.DefaultTag + "############ Failed Tests - Failures: ", summary.FailureCount, ColorStyle.Failure);
+ WriteSummaryCount(", Errors: ", summary.ErrorCount, ColorStyle.Error);
+ WriteSummaryCount(", Invalid: ", summary.InvalidCount, ColorStyle.Error);
+ _writer.WriteLine();
+ }
+ if (summary.TotalSkipCount > 0)
+ {
+ WriteSummaryCount(TLogger.DefaultTag + "############ Skipped Tests - Ignored: ", summary.IgnoreCount, ColorStyle.Warning);
+ WriteSummaryCount(", Explicit: ", summary.ExplicitCount);
+ WriteSummaryCount(", Other: ", summary.SkipCount);
+ _writer.WriteLine();
+ }
+
+ _writer.WriteLabelLine(TLogger.DefaultTag + "############ Start time: ", summary.StartTime.ToString("u"));
+ _writer.WriteLabelLine(TLogger.DefaultTag + "############ End time: ", summary.EndTime.ToString("u"));
+ _writer.WriteLabelLine(TLogger.DefaultTag + "############ Duration: ", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000} seconds", summary.Duration));
+ _writer.WriteLine();
+ }
+
+ private void WriteSummaryCount(string label, int count)
+ {
+ _writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture));
+ }
+
+ private void WriteSummaryCount(string label, int count, ColorStyle color)
+ {
+ _writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture), count > 0 ? color : ColorStyle.Value);
+ }
+
+ #endregion
+
+ #region DisplayErrorsAndFailuresReport
+
+ public void DisplayErrorsAndFailuresReport(ITestResult result)
+ {
+ _reportIndex = 0;
+ WriteSectionHeader(" ");
+ WriteSectionHeader("######################################################################################");
+ WriteSectionHeader("############################## ERRORS AND FAILURES ###################################");
+ DisplayErrorsAndFailures(result);
+ _writer.WriteLine();
+
+#if !SILVERLIGHT
+ if (_options.StopOnError)
+ {
+ _writer.WriteLine(ColorStyle.Failure, "Execution terminated after first error");
+ _writer.WriteLine();
+ }
+#endif
+ }
+
+ #endregion
+
+ #region DisplayNotRunReport
+
+ public void DisplayNotRunReport(ITestResult result)
+ {
+ _reportIndex = 0;
+ WriteSectionHeader("Tests Not Run");
+
+ DisplayNotRunResults(result);
+
+ _writer.WriteLine();
+ }
+
+ #endregion
+
+ #region DisplayFullReport
+
+#if FULL // Not currently used, but may be reactivated
+ /// <summary>
+ /// Prints a full report of all results
+ /// </summary>
+ public void DisplayFullReport(ITestResult result)
+ {
+ WriteLine(ColorStyle.SectionHeader, "All Test Results -");
+ _writer.WriteLine();
+
+ DisplayAllResults(result, " ");
+
+ _writer.WriteLine();
+ }
+#endif
+
+ #endregion
+
+ #endregion
+
+ #region DisplayWarning
+
+ public void DisplayWarning(string text)
+ {
+ _writer.WriteLine(ColorStyle.Warning, text);
+ }
+
+ #endregion
+
+ #region DisplayError
+
+ public void DisplayError(string text)
+ {
+ _writer.WriteLine(ColorStyle.Error, text);
+ }
+
+ #endregion
+
+ #region DisplayErrors
+
+ public void DisplayErrors(IList<string> messages)
+ {
+ foreach (string message in messages)
+ DisplayError(message);
+ }
+
+ #endregion
+
+ #endregion
+
+ #region Helper Methods
+
+ private void DisplayErrorsAndFailures(ITestResult result)
+ {
+ if (result.Test.IsSuite)
+ {
+ if (result.ResultState.Status == TestStatus.Failed)
+ {
+ var suite = result.Test as TestSuite;
+ var site = result.ResultState.Site;
+ if (suite.TestType == "Theory" || site == FailureSite.SetUp || site == FailureSite.TearDown)
+ DisplayTestResult(result);
+ if (site == FailureSite.SetUp) return;
+ }
+
+ foreach (ITestResult childResult in result.Children)
+ DisplayErrorsAndFailures(childResult);
+ }
+ else if (result.ResultState.Status == TestStatus.Failed)
+ DisplayTestResult(result);
+ }
+
+ private void DisplayNotRunResults(ITestResult result)
+ {
+ if (result.HasChildren)
+ foreach (ITestResult childResult in result.Children)
+ DisplayNotRunResults(childResult);
+ else if (result.ResultState.Status == TestStatus.Skipped)
+ DisplayTestResult(result);
+ }
+
+ private static readonly char[] TRIM_CHARS = new char[] { '\r', '\n' };
+ private int _reportIndex;
+
+ private void DisplayTestResult(ITestResult result)
+ {
+ string status = result.ResultState.Label;
+ if (string.IsNullOrEmpty(status))
+ status = result.ResultState.Status.ToString();
+
+ if (status == "Failed" || status == "Error")
+ {
+ var site = result.ResultState.Site.ToString();
+ if (site == "SetUp" || site == "TearDown")
+ status = site + " " + status;
+ }
+
+ ColorStyle style = ColorStyle.Output;
+ switch (result.ResultState.Status)
+ {
+ case TestStatus.Failed:
+ style = ColorStyle.Failure;
+ break;
+ case TestStatus.Skipped:
+ style = status == "Ignored" ? ColorStyle.Warning : ColorStyle.Output;
+ break;
+ case TestStatus.Passed:
+ style = ColorStyle.Pass;
+ break;
+ }
+
+ _writer.WriteLine();
+ _writer.WriteLine(
+ style, string.Format("{0}) {1} : {2}", ++_reportIndex, status, result.FullName));
+
+ if (!string.IsNullOrEmpty(result.Message))
+ {
+ string[] messages = result.Message.TrimEnd(TRIM_CHARS).Split(TRIM_CHARS);
+ foreach (string message in messages)
+ _writer.WriteLine(style, message);
+ }
+
+ if (!string.IsNullOrEmpty(result.StackTrace))
+ {
+ string[] stackTraces = result.StackTrace.TrimEnd(TRIM_CHARS).Split(TRIM_CHARS);
+ foreach (string stackTrace in stackTraces)
+ _writer.WriteLine(style, stackTrace);
+ }
+ }
+
+#if FULL
+ private void DisplayAllResults(ITestResult result, string indent)
+ {
+ string status = null;
+ ColorStyle style = ColorStyle.Output;
+ switch (result.ResultState.Status)
+ {
+ case TestStatus.Failed:
+ status = "FAIL";
+ style = ColorStyle.Failure;
+ break;
+ case TestStatus.Skipped:
+ if (result.ResultState.Label == "Ignored")
+ {
+ status = "IGN ";
+ style = ColorStyle.Warning;
+ }
+ else
+ {
+ status = "SKIP";
+ style = ColorStyle.Output;
+ }
+ break;
+ case TestStatus.Inconclusive:
+ status = "INC ";
+ style = ColorStyle.Output;
+ break;
+ case TestStatus.Passed:
+ status = "OK ";
+ style = ColorStyle.Pass;
+ break;
+ }
+
+ WriteLine(style, status + indent + result.Name);
+
+ if (result.HasChildren)
+ foreach (ITestResult childResult in result.Children)
+ PrintAllResults(childResult, indent + " ");
+ }
+#endif
+
+ private void WriteHeader(string text)
+ {
+ _writer.WriteLine(ColorStyle.Header, text);
+ }
+
+ private void WriteSubHeader(string text)
+ {
+ _writer.WriteLine(ColorStyle.SubHeader, text);
+ }
+
+ private void WriteSectionHeader(string text)
+ {
+ _writer.WriteLine(ColorStyle.SectionHeader, text);
+ }
+
+ private void WriteHelpLine(string text)
+ {
+ _writer.WriteLine(ColorStyle.Help, text);
+ }
+
+ private string _currentLabel;
+
+ private void WriteLabelLine(string label)
+ {
+ if (label != _currentLabel)
+ {
+ _writer.WriteLine(ColorStyle.SectionHeader, "=> " + label);
+ _testCreatedOutput = true;
+ _currentLabel = label;
+ }
+ }
+
+ private void WriteOutputLine(string text)
+ {
+ WriteOutputLine(ColorStyle.Output, text);
+ }
+
+ private void WriteOutputLine(ColorStyle color, string text)
+ {
+ _writer.Write(color, text);
+
+ if (!text.EndsWith(Environment.NewLine))
+ _writer.WriteLine();
+
+ _testCreatedOutput = true;
+ }
+
+ #endregion
+ }
+}
--- /dev/null
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <OutputType>Library</OutputType>
+ <TargetFramework>netstandard2.0</TargetFramework>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\nunit.framework\nunit.framework.csproj" />
+ </ItemGroup>
+
+</Project>
-
-using global::System;
-using Tizen.NUI;
+/*
+ * Copyright(c) 2022 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
using Tizen.NUI.BaseComponents;
-using NUnit.Framework;
namespace Tizen.NUI.Samples
{
using log = Tizen.Log;
public class SubWindowTest : IExample
{
- string tag = "NUITEST";
- Window mainWin;
- Window subWin1;
- Window subWin2;
- Window subWin3;
- Timer tm;
- bool belowParent;
- void Initialize()
+ private const string tag = "NUITEST";
+ private const string KEY_BACK = "XF86Back";
+ private const string KEY_ESCAPE = "Escape";
+ private const string KEY_NUM_1 = "1";
+ private const string KEY_NUM_2 = "2";
+ private const string KEY_NUM_3 = "3";
+ private const string KEY_NUM_4 = "4";
+ private const string KEY_NUM_5 = "5";
+ private const string KEY_PARENT_ABOVE = "6";
+ private const string KEY_PARENT_BELOW = "7";
+ private Window mainWin;
+ private Window subWinFirst;
+ private Window subWinSecond;
+ private Window subWinThird;
+ private Timer disposeTimer;
+ private bool belowParent;
+ private const int oneSecond = 1000;
+ private const int testSize = 100;
+ private const int testPosition = 100;
+ private const float testPointSize = 12.0f;
+
+ public void Activate()
+ {
+ Initialize();
+ }
+
+ public void Deactivate()
+ {
+ }
+
+ private void Initialize()
{
mainWin = NUIApplication.GetDefaultWindow();
mainWin.KeyEvent += OnKeyEvent;
mainWin.BackgroundColor = Color.Cyan;
- mainWin.WindowSize = new Size2D(500, 500);
+ mainWin.WindowSize = new Size2D(5 * testSize, 5 * testSize);
mainWin.TouchEvent += WinTouchEvent;
belowParent = false;
- TextLabel text = new TextLabel("Hello Tizen NUI World");
- text.HorizontalAlignment = HorizontalAlignment.Center;
- text.VerticalAlignment = VerticalAlignment.Center;
- text.TextColor = Color.Blue;
- text.PointSize = 12.0f;
- text.HeightResizePolicy = ResizePolicyType.FillToParent;
- text.WidthResizePolicy = ResizePolicyType.FillToParent;
- mainWin.Add(text);
+ TextLabel testText = new TextLabel("Hello Tizen NUI World")
+ {
+ HorizontalAlignment = HorizontalAlignment.Center,
+ VerticalAlignment = VerticalAlignment.Center,
+ TextColor = Color.Blue,
+ PointSize = testPointSize,
+ HeightResizePolicy = ResizePolicyType.FillToParent,
+ WidthResizePolicy = ResizePolicyType.FillToParent
+ };
+ mainWin.Add(testText);
- Animation animation = new Animation(2000);
- animation.AnimateTo(text, "Orientation", new Rotation(new Radian(new Degree(180.0f)), PositionAxis.X), 0, 500);
- animation.AnimateTo(text, "Orientation", new Rotation(new Radian(new Degree(0.0f)), PositionAxis.X), 500, 1000);
- animation.Looping = true;
- animation.Play();
+ Animation testRotationAnim = new Animation(2 * oneSecond);
+ testRotationAnim.AnimateTo(testText, "Orientation", new Rotation(new Radian(new Degree(180.0f)), PositionAxis.X), 0, oneSecond);
+ testRotationAnim.AnimateTo(testText, "Orientation", new Rotation(new Radian(new Degree(0.0f)), PositionAxis.X), oneSecond, 2 * oneSecond);
+ testRotationAnim.Looping = true;
+ testRotationAnim.Play();
- log.Fatal(tag, "animation play!");
+ log.Debug(tag, "animation play!");
}
- void CreateSubWin3()
+ private void CreateSubWinThird()
{
- if(subWin3)
+ if (subWinThird)
{
- log.Fatal(tag, $"Sub Window3 is already created");
+ log.Debug(tag, $"subWinThird is already created");
return;
}
- subWin3 = new Window("subWin3", new Rectangle(0, 0, 300, 300), false);
- subWin3.BackgroundColor = Color.Blue;
- View dummy = new View()
+ subWinThird = new Window("subWinThird", new Rectangle(0, 0, 3 * testSize, 3 * testSize), false)
{
- Size = new Size(100, 100),
- Position = new Position(50, 50),
+ BackgroundColor = Color.Blue
+ };
+ View childDummyView = new View()
+ {
+ Size = new Size(testSize, testSize),
+ Position = new Position(testPosition, testPosition),
BackgroundColor = Color.Yellow,
};
- subWin3.Add(dummy);
- subWin3.KeyEvent += subWin3_KeyEvent;
+ subWinThird.Add(childDummyView);
+ subWinThird.KeyEvent += SubWinThirdKeyEvent;
}
- void SetParentAbove()
+ private void SetParentAbove()
{
- CreateSubWin3();
- subWin3.SetParent(mainWin, false);
+ CreateSubWinThird();
+ subWinThird.SetParent(mainWin, false);
}
- void SetParentBelow()
+ private void SetParentBelow()
{
- CreateSubWin3();
- subWin3.SetParent(mainWin, true);
+ CreateSubWinThird();
+ subWinThird.SetParent(mainWin, true);
}
- public void subWin3_KeyEvent(object sender, Window.KeyEventArgs e)
+ private void SubWinThirdKeyEvent(object sender, Window.KeyEventArgs e)
{
if (e.Key.State == Key.StateType.Down)
{
- log.Fatal(tag, $"key down! key={e.Key.KeyPressedName}");
+ log.Debug(tag, $"key down! key={e.Key.KeyPressedName}");
switch (e.Key.KeyPressedName)
{
- case "6":
+ case KEY_PARENT_ABOVE:
SetParentAbove();
break;
- case "7":
+ case KEY_PARENT_BELOW:
SetParentBelow();
break;
}
}
}
- public void WinTouchEvent(object sender, Window.TouchEventArgs e)
+ private void WinTouchEvent(object sender, Window.TouchEventArgs e)
{
if (e.Touch.GetState(0) == PointStateType.Up)
{
- if(belowParent == false)
+ if (belowParent == false)
{
SetParentBelow();
belowParent = true;
}
}
- public void OnKeyEvent(object sender, Window.KeyEventArgs e)
+ private void OnKeyEvent(object sender, Window.KeyEventArgs e)
{
if (e.Key.State == Key.StateType.Down)
{
- log.Fatal(tag, $"key down! key={e.Key.KeyPressedName}");
+ log.Debug(tag, $"key down! key={e.Key.KeyPressedName}");
switch (e.Key.KeyPressedName)
{
- case "XF86Back":
- case "Escape":
- //Exit();
+ case KEY_BACK:
+ case KEY_ESCAPE:
break;
- case "1":
- TestCase1();
+ case KEY_NUM_1:
+ TestMakeSubWindowAndAddSomeDummyObject();
break;
- case "2":
- TestCase2();
+ case KEY_NUM_2:
+ TestDisposeSubWindowFirstWhichWasCreatedInPrivousTestCase();
break;
- case "3":
- TestCase3();
+ case KEY_NUM_3:
+ TestCreateSubWindowSecondWhichDoesNotHaveAnySettingAndDisposeItAfterThreeSecondsDelay();
break;
- case "4":
- TestCase4();
+ case KEY_NUM_4:
+ TestCreateSubWindowSecondWhichHasSomeSettingAndDisposeItAfterThreeSecondsDelay();
break;
- case "5":
- TestCase5();
+ case KEY_NUM_5:
+ TestCreateSubWindowSecondWhichHasSomeSettingAndAddSomeDummyObjectAndDisposeItAfterThreeSecondsDelay();
break;
- case "6":
+ case KEY_PARENT_ABOVE:
SetParentAbove();
break;
- case "7":
+ case KEY_PARENT_BELOW:
SetParentBelow();
break;
default:
- log.Fatal(tag, $"no test!");
+ log.Debug(tag, $"no test!");
break;
}
}
}
//TDD
- void TestCase1()
+ private void TestMakeSubWindowAndAddSomeDummyObject()
{
- log.Fatal(tag, "test 1 : 1) make sub window-1 2) add some dummy object");
-
- subWin1 = new Window("subwin1", new Rectangle(500, 500, 300, 300), false);
- subWin1.BackgroundColor = Color.Blue;
- View dummy = new View()
+ subWinFirst = new Window("subWinFirst", new Rectangle(5 * testPosition, 5 * testPosition, 3 * testSize, 3 * testSize), false)
{
- Size = new Size(100, 100),
- Position = new Position(50, 50),
+ BackgroundColor = Color.Blue
+ };
+ View childView = new View()
+ {
+ Size = new Size(testSize, testSize),
+ Position = new Position(testPosition, testPosition),
BackgroundColor = Color.Yellow,
};
- subWin1.Add(dummy);
- subWin1.KeyEvent += SubWin1_KeyEvent;
+ subWinFirst.Add(childView);
+ subWinFirst.KeyEvent += SubWinFirstKeyEvent;
}
- void TestCase2()
+
+ private void TestDisposeSubWindowFirstWhichWasCreatedInPrivousTestCase()
{
- log.Fatal(tag, "test 2 : 1) do dispose of sub window-1 created in #1");
- subWin1?.Dispose();
+ subWinFirst?.Dispose();
}
- void TestCase3()
+
+ private void TestCreateSubWindowSecondWhichDoesNotHaveAnySettingAndDisposeItAfterThreeSecondsDelay()
{
- log.Fatal(tag, $"test 3 : 1) create sub window2 which doesn't have any setting 2) dispose it after 3 second delay");
- subWin2 = null;
- subWin2 = new Window();
- tm = new Timer(3000);
- tm.Tick += Tm_Tick;
- tm.Start();
+ subWinSecond = null;
+ subWinSecond = new Window();
+ disposeTimer = new Timer(3 * oneSecond);
+ disposeTimer.Tick += OnDisposeTimerTick;
+ disposeTimer.Start();
}
- void TestCase4()
+
+ private void TestCreateSubWindowSecondWhichHasSomeSettingAndDisposeItAfterThreeSecondsDelay()
{
- log.Fatal(tag, $"test 4 : 1) create sub window2 which has some setting 2) dispose it after 3 second delay");
- subWin2 = null;
- subWin2 = new Window("subWin2", new Rectangle(100, 100, 100, 100), false);
- subWin2.BackgroundColor = Color.Red;
- tm = new Timer(3000);
- tm.Tick += Tm_Tick;
- tm.Start();
+ subWinSecond = null;
+ subWinSecond = new Window("subWinSecond", new Rectangle(testPosition, testPosition, testSize, testSize), false)
+ {
+ BackgroundColor = Color.Red
+ };
+ disposeTimer = new Timer(3 * oneSecond);
+ disposeTimer.Tick += OnDisposeTimerTick;
+ disposeTimer.Start();
}
- void TestCase5()
+
+ private void TestCreateSubWindowSecondWhichHasSomeSettingAndAddSomeDummyObjectAndDisposeItAfterThreeSecondsDelay()
{
- log.Fatal(tag, $"test 5 : 1) create sub window2 which has some setting 2) add some dummy object 3) dispose it after 3 second delay");
- subWin2 = null;
- subWin2 = new Window("subWin2", new Rectangle(500, 500, 300, 300), false);
- subWin2.BackgroundColor = Color.Red;
- View v1 = new View()
+ subWinSecond = null;
+ subWinSecond = new Window("subWinSecond", new Rectangle(5 * testPosition, 5 * testPosition, 3 * testSize, 3 * testSize), false)
+ {
+ BackgroundColor = Color.Red
+ };
+ View testView = new View()
{
- Size = new Size(50, 50),
- Position = new Position(50, 50),
+ Size = new Size(testSize, testSize),
+ Position = new Position(testPosition, testPosition),
BackgroundColor = Color.Yellow,
};
- subWin2.Add(v1);
+ subWinSecond.Add(testView);
- tm = new Timer(3000);
- tm.Tick += Tm_Tick;
- tm.Start();
+ disposeTimer = new Timer(3 * oneSecond);
+ disposeTimer.Tick += OnDisposeTimerTick;
+ disposeTimer.Start();
}
- private bool Tm_Tick(object source, Timer.TickEventArgs e)
+ private bool OnDisposeTimerTick(object source, Timer.TickEventArgs e)
{
- log.Fatal(tag, $"after 3000ms, subwin2 dispose!");
- subWin2?.Dispose();
+ log.Debug(tag, $"after 3000ms, subWinSecond dispose!");
+ subWinSecond?.Dispose();
return false;
}
- private void SubWin1_KeyEvent(object sender, Window.KeyEventArgs e)
+ private void SubWinFirstKeyEvent(object sender, Window.KeyEventArgs e)
{
if (e.Key.State == Key.StateType.Down)
{
- log.Fatal(tag, $"subWin1 key down! key={e.Key.KeyPressedName}");
+ log.Debug(tag, $"subWinFirst key down! key={e.Key.KeyPressedName}");
switch (e.Key.KeyPressedName)
{
- case "XF86Back":
- case "Escape":
- //Exit();
+ case KEY_BACK:
+ case KEY_ESCAPE:
break;
- case "1":
+ case KEY_NUM_1:
mainWin.Raise();
break;
default:
- log.Fatal(tag, $"default!");
+ log.Debug(tag, $"default!");
break;
}
}
}
-
-
- public void Activate() { Initialize(); }
- public void Deactivate() { }
}
}
{
Enable = true,
Color = new Color("#3498DB"),
- Height = 2.0f
+ Height = 2.0f,
+ Type = UnderlineType.Solid,
+ DashWidth = 5.0f,
+ DashGap = 3.0f,
};
using (PropertyMap map = TextMapHelper.GetUnderlineMap(underline))
map.Find(0, "enable").Get(out bool enable);
map.Find(0, "color").Get(color);
map.Find(0, "height").Get(out float height);
+ map.Find(0, "type").Get(out int type);
+ map.Find(0, "dashWidth").Get(out float dashWidth);
+ map.Find(0, "dashGap").Get(out float dashGap);
Assert.AreEqual(enable, underline.Enable, "Should be equal!");
Assert.AreEqual(height, underline.Height, "Should be equal!");
Assert.AreEqual(true, CheckColor(color, underline.Color), "Should be true!");
+ Assert.AreEqual(type, (int)underline.Type, "Should be equal!");
+ Assert.AreEqual(dashWidth, underline.DashWidth, "Should be equal!");
+ Assert.AreEqual(dashGap, underline.DashGap, "Should be equal!");
+
color.Dispose();
}
{
tlog.Debug(tag, $"TextMapHelperGetIntFromMap START");
+ var stringKey = "width";
+ var stringInvalidKey = "invalidKey";
var intKey = 1;
var intInvalidKey = 10;
var value = 3080;
using (var map = new PropertyMap())
{
+ map.Add(stringKey, value);
map.Add(intKey, value);
- var result = TextMapHelper.GetIntFromMap(map, intKey, defaultValue);
+ var result = TextMapHelper.GetIntFromMap(map, stringKey, defaultValue);
+ Assert.AreEqual(value, result, "Should be equal!");
+
+ result = TextMapHelper.GetIntFromMap(map, stringInvalidKey, defaultValue);
+ Assert.AreEqual(defaultValue, result, "Should be equal!");
+
+ result = TextMapHelper.GetIntFromMap(map, intKey, defaultValue);
Assert.AreEqual(value, result, "Should be equal!");
result = TextMapHelper.GetIntFromMap(map, intInvalidKey, defaultValue);
{
tlog.Debug(tag, $"TextMapHelperGetNullableFloatFromMap START");
+ var stringKey = "width";
+ var stringInvalidKey = "invalidKey";
var intKey = 1;
var intInvalidKey = 10;
float value = 3.14f;
using (var map = new PropertyMap())
{
+ map.Add(stringKey, value);
map.Add(intKey, value);
+ result = TextMapHelper.GetNullableFloatFromMap(map, stringKey);
+ Assert.AreEqual(value, result, "Should be equal!");
+
+ result = TextMapHelper.GetNullableFloatFromMap(map, stringInvalidKey);
+ Assert.AreEqual(null, result, "Should be equal!");
+
result = TextMapHelper.GetNullableFloatFromMap(map, intKey);
Assert.AreEqual(value, result, "Should be equal!");