elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Como proteger una cartera - billetera de Bitcoin


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [SOURCE-CODE] Repositorio de tests de unidad y tests de integración para .NET
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [SOURCE-CODE] Repositorio de tests de unidad y tests de integración para .NET  (Leído 2,455 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.813



Ver Perfil
[SOURCE-CODE] Repositorio de tests de unidad y tests de integración para .NET
« en: 16 Diciembre 2016, 02:20 am »



¡Buenas!

Me pareció original la idea de publicar este tema para que podamos compartir tests de unidad (Unit Test) y/o tests de integración (Integration Test) que sean reutilizables,
como una especie de snippets de código. Y así mentener nuestros proyectos libres de bugs.



Test de Evaluación del Tamaño de Estructuras

El siguiente test, sirve para evaluar el tamaño de la instancia de las estructuras definidas en un ensamblado.

El test fallará en caso de que el tamaño de "X" instancia sea menor que el mínimo recomendado (8 bytes) o mayor que el máximo recomendado (16 bytes) según las directrices de diseño de Microsoft .NET.

Este ejemplo, lejos de ilustrar como se debe escribir un test siguiendo buenas prácticas para evaluar cada estructura por individual, lo he diseñado de tal forma que se pueda automatizar a gran escala,
es un código reutilizable que se puede adaptar con el menor esfuerzo solo haciendo un copy&paste; para ello he recurrido a Reflection, de esta manera podemos cargar los
ensamblados referenciados que especifiquemos en un Array de tipo String(), y obtener y evaluar todas las estructuras visibles de dichos ensamblados.

Configuración Del Test:

Esta class nos servirá para mantener una referencia de los (nombres de) ensamblados que se evaluarán en el test.
Como es evidente, los ensamblados deberán estar referenciados en el proyecto de Unit Testing:


Código
  1. Public NotInheritable Class Fields
  2.  
  3.    ''' ----------------------------------------------------------------------------------------------------
  4.    ''' <summary>
  5.    ''' The referenced assembly names to test their members.
  6.    ''' </summary>
  7.    ''' ----------------------------------------------------------------------------------------------------
  8.    Public Shared ReadOnly AssemblyNames As String() = {
  9.        "Microsoft.VisualStudio.QualityTools.UnitTestFramework",
  10.        "..."
  11.    }
  12.  
  13.    ''' ----------------------------------------------------------------------------------------------------
  14.    ''' <summary>
  15.    ''' The minimum recommended size for a Structure type.
  16.    ''' </summary>
  17.    ''' ----------------------------------------------------------------------------------------------------
  18.    ''' <remarks>
  19.    ''' <see href="http://stackoverflow.com/a/1082340/1248295"/>
  20.    ''' </remarks>
  21.    ''' ----------------------------------------------------------------------------------------------------
  22.    Public Shared ReadOnly MinimumRecommendedStructureSize As Integer = 8
  23.  
  24.    ''' ----------------------------------------------------------------------------------------------------
  25.    ''' <summary>
  26.    ''' The maximum recommended size for a Structure type.
  27.    ''' </summary>
  28.    ''' ----------------------------------------------------------------------------------------------------
  29.    ''' <remarks>
  30.    ''' <see href="http://msdn.microsoft.com/en-us/library/ms229017.aspx"/>
  31.    ''' </remarks>
  32.    ''' ----------------------------------------------------------------------------------------------------
  33.    Public Shared ReadOnly MaximumRecommendedStructureSize As Integer = 16
  34.  
  35.    Private Sub New()
  36.    End Sub
  37.  
  38. End Class

El Test:

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 15-December-2016
  4. ' ***********************************************************************
  5.  
  6. Option Strict On
  7. Option Explicit On
  8. Option Infer Off
  9.  
  10. Imports Microsoft.VisualStudio.TestTools.UnitTesting
  11. Imports System.Reflection
  12. Imports System.Runtime.InteropServices
  13.  
  14. ''' <summary>
  15. ''' Performs various tests on the <see langword="Structure"/> members of all the assemblies defined in
  16. ''' <see cref="Fields.AssemblyNames"/>.
  17. ''' </summary>
  18. <TestClass()>
  19. Public Class StructureTests
  20.  
  21. #Region " Test Methods "
  22.  
  23.    ''' <summary>
  24.    ''' Performs a test on the <see langword="Structure"/> members of all the assemblies defined in
  25.    ''' <see cref="Fields.AssemblyNames"/>,
  26.    ''' to determine whether a structure has the proper instance size regarding to .NET design guidelines.
  27.    ''' </summary>
  28.    <TestMethod()>
  29.    <TestCategory("Structures")>
  30.    Public Sub TestStructureSizes()
  31.  
  32.        Dim testFailed As Boolean = False
  33.        Dim testException As AssertFailedException = Nothing
  34.  
  35.        ' Safe Structures to exclude in this test.
  36.        ' ----------------------------------------
  37.        ' These structures could be smaller or bigger than what is recommended, however, are not considered an error.
  38.        Dim excludedStructs As String() = {
  39.            "MyNamespace.MyStructure"
  40.        }
  41.  
  42.        For Each assName As String In Fields.AssemblyNames
  43.  
  44.            Dim ass As Assembly = Assembly.Load(assName)
  45.            Debug.WriteLine(String.Format("Testing Assembly '{0}.dll'...", assName))
  46.            Debug.WriteLine(String.Empty)
  47.  
  48.            Dim excludedStructures As IEnumerable(Of Type) =
  49.                From t As Type In ass.GetTypes()
  50.                Where (t.IsValueType) AndAlso (Not t.IsClass) AndAlso (Not t.IsEnum) AndAlso (t.IsVisible)
  51.                Where excludedStructs.Contains(String.Format("{0}.{1}", t.Namespace, t.Name))
  52.                Order By String.Format("{0}.{1}", t.Namespace, t.Name)
  53.  
  54.            Dim includedStructures As IEnumerable(Of Type) =
  55.                From t As Type In ass.GetTypes()
  56.                Where (t.IsValueType) AndAlso (Not t.IsClass) AndAlso (Not t.IsEnum) AndAlso (t.IsVisible)
  57.                Where Not excludedStructs.Contains(String.Format("{0}.{1}", t.Namespace, t.Name))
  58.                Order By String.Format("{0}.{1}", t.Namespace, t.Name)
  59.  
  60.            If (excludedStructures.Count <> 0) Then
  61.                Debug.WriteLine(String.Format("    Excluded Structures:"))
  62.                For Each t As Type In excludedStructures
  63.                    Debug.WriteLine(String.Format("        '{0}.{1}')",
  64.                                              t.Namespace, t.Name))
  65.                Next t
  66.                Debug.WriteLine(String.Empty)
  67.            End If
  68.  
  69.            If (includedStructures.Count <> 0) Then
  70.                For Each t As Type In includedStructures
  71.                    Try
  72.                        Me.EvaluateStructureSize(t)
  73.  
  74.                    Catch ex As AssertFailedException
  75.                        Debug.WriteLine(String.Format("    Testing Structure '{0}.{1}' ({2} Bytes)... FAIL", t.Namespace, t.Name, Marshal.SizeOf(t)))
  76.                        If (testException Is Nothing) Then
  77.                            testException = ex
  78.                            testFailed = True
  79.                        End If
  80.  
  81.                    Catch ex As Exception
  82.                        Debug.WriteLine(String.Format("    Testing Structure '{0}.{1}'... ERROR. EXCEPTION THROWN.",
  83.                                                      t.Namespace, t.Name))
  84.                        Debug.WriteLine("EXCEPTION MESSAGE:")
  85.                        Debug.WriteLine(ex.Message)
  86.                        Throw
  87.  
  88.                    End Try
  89.  
  90.                Next t
  91.                Debug.WriteLine(String.Empty)
  92.            End If
  93.  
  94.            If (testFailed) Then
  95.                Throw testException
  96.            End If
  97.  
  98.        Next assName
  99.  
  100.    End Sub
  101.  
  102. #End Region
  103.  
  104. #Region " Private Methods "
  105.  
  106.    ''' <summary>
  107.    ''' Determines whether the instance size of a structure is smaller and/or greater than the size recommended.
  108.    ''' </summary>
  109.    Private Sub EvaluateStructureSize(ByVal t As Type)
  110.  
  111.        Dim currentStructureSize As Integer = Marshal.SizeOf(t)
  112.  
  113.        Assert.IsTrue((currentStructureSize >= Fields.MinimumRecommendedStructureSize),
  114.                        String.Format("The current instance size of Structure '{0}.{1}' is {2} bytes, which is smaller than the minimum recommended {3} bytes.",
  115.                                      t.Namespace, t.Name, currentStructureSize, Fields.MinimumRecommendedStructureSize))
  116.  
  117.        Assert.IsTrue((currentStructureSize <= Fields.MaximumRecommendedStructureSize),
  118.                        String.Format("The current instance size of Structure '{0}.{1}' is {2} bytes, which is greater than the maximum recommended {3} bytes.",
  119.                                      t.Namespace, t.Name, currentStructureSize, Fields.MaximumRecommendedStructureSize))
  120.  
  121.        Debug.WriteLine(String.Format("    Testing Structure '{0}.{1}' ({2} Bytes)... Ok", t.Namespace, t.Name, currentStructureSize))
  122.  
  123.    End Sub
  124.  
  125. #End Region
  126.  
  127. End Class


Resultado de Test Satisfactorio:

Citar
Test Name:  TestStructureSizes
Test Outcome:   Passed
Result StandardOutput:  
Debug Trace:

Testing Assembly 'Elektro.Application.dll'...

    Testing Structure 'Elektro.Application.UI.Types.NonClientAreaMargins' (16 Bytes)... Ok

Testing Assembly 'Elektro.Application.ThirdParty.dll'...

Testing Assembly 'Elektro.Core.dll'...

    Testing Structure 'Elektro.Core.Text.RegEx.Types.MatchPositionInfo' (16 Bytes)... Ok

Testing Assembly 'Elektro.Imaging.dll'...

Testing Assembly 'Elektro.Interop.dll'...

    Excluded Structures:
        'Elektro.Interop.Win32.Types.AppbarData')
        'Elektro.Interop.Win32.Types.BlendFunction')
        'Elektro.Interop.Win32.Types.CallWndProcStruct')
        ...

Testing Assembly 'Elektro.Multimedia.dll'...

    Testing Structure 'Elektro.Multimedia.Types.StereoVolume' (8 Bytes)... Ok

Testing Assembly 'Elektro.Net.dll'...

Testing Assembly 'Elektro.Processes.dll'...

Testing Assembly 'Elektro.System.dll'...



Reporte de Test Fallido:



« Última modificación: 16 Diciembre 2016, 03:06 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.813



Ver Perfil
Re: [SOURCE-CODE] Repositorio de tests de unidad y tests de integración para .NET
« Respuesta #1 en: 16 Diciembre 2016, 02:21 am »

Test Para Descubrir Valores Duplicados en Enums

El siguiente test, sirve para determinar si alguna de las Enums definidas en un ensamblado contiene valores duplicados (e indeseados), y qué valores son esos.

El test fallará en caso de que "X" Enum contenga al menos 1 valor duplicado. Se pueden excluir enumeraciones en el test.

Este ejemplo lo he diseñado de tal forma que se pueda automatizar a gran escala, es un código reutilizable que se puede adaptar con el menor esfuerzo solo haciendo un copy&paste;
para ello he recurrido a Reflection, de esta manera podemos cargar los ensamblados referenciados que especifiquemos en un Array de tipo String(),
y obtener y evaluar todas las enumeraciones visibles de dichos ensamblados.

Ejemplo de una Enum con valores duplicados:

Código
  1. Public Enum MyEnum As Integer
  2.    Name1 = 0
  3.    Name2 = 1
  4.    Name3 = 1
  5.    Name4 = MyEnum.Name1
  6. End Enum

Configuración Del Test:

Esta class nos servirá para mantener una referencia de los (nombres de) ensamblados que se evaluarán en el test.
Como es evidente, los ensamblados deberán estar referenciados en el proyecto de Unit Testing:


Código
  1. Public NotInheritable Class Fields
  2.  
  3.    ''' ----------------------------------------------------------------------------------------------------
  4.    ''' <summary>
  5.    ''' The referenced assembly names to test their members.
  6.    ''' </summary>
  7.    ''' ----------------------------------------------------------------------------------------------------
  8.    Public Shared ReadOnly AssemblyNames As String() = {
  9.        "Microsoft.VisualStudio.QualityTools.UnitTestFramework",
  10.        "..."
  11.    }
  12.  
  13.    Private Sub New()
  14.    End Sub
  15.  
  16. End Class


El Test:

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 15-December-2016
  4. ' ***********************************************************************
  5.  
  6. Option Strict On
  7. Option Explicit On
  8. Option Infer Off
  9.  
  10. Imports Microsoft.VisualStudio.TestTools.UnitTesting
  11. Imports System.Reflection
  12.  
  13. ''' <summary>
  14. ''' Performs various tests on the <see cref="[Enum]"/> members of all the assemblies defined in
  15. ''' <see cref="Fields.AssemblyNames"/>.
  16. ''' </summary>
  17. <TestClass()>
  18. Public Class EnumTests
  19.  
  20. #Region " Test Methods "
  21.  
  22.    ''' <summary>
  23.    ''' Performs a test on the <see cref="[Enum]"/> members of all the assemblies defined in
  24.    ''' <see cref="Fields.AssemblyNames"/>,
  25.    ''' to determine whether a <see cref="[Enum]"/> contains duplicated values.
  26.    ''' </summary>
  27.    <TestMethod()>
  28.    <TestCategory("Enums")>
  29.    Public Sub TestEnumDuplicatedValues()
  30.  
  31.        Dim testFailed As Boolean = False
  32.        Dim testException As AssertFailedException = Nothing
  33.  
  34.        ' Safe Enums to exclude in this test.
  35.        ' -----------------------------------
  36.        ' These enums could contain duplicated values, however, are not considered a bug,
  37.        ' they are defined like that for design purposes.
  38.        Dim excludedEnums As String() = {
  39.            "MyNamespace.MyEnum"
  40.        }
  41.  
  42.        For Each assName As String In Fields.AssemblyNames
  43.  
  44.            Dim ass As Assembly = Assembly.Load(assName)
  45.            Debug.WriteLine(String.Format("Testing Assembly '{0}.dll'...", assName))
  46.            Debug.WriteLine(String.Empty)
  47.  
  48.            Dim excludedTypes As IEnumerable(Of Type) =
  49.                From t As Type In ass.GetLoadableTypes()
  50.                Where t.IsEnum
  51.                Where excludedEnums.Contains(String.Format("{0}.{1}", t.Namespace, t.Name))
  52.                Order By String.Format("{0}.{1}", t.Namespace, t.Name)
  53.  
  54.            Dim includedTypes As IEnumerable(Of Type) =
  55.                From t As Type In ass.GetLoadableTypes()
  56.                Where t.IsEnum
  57.                Where Not excludedEnums.Contains(String.Format("{0}.{1}", t.Namespace, t.Name))
  58.                Order By String.Format("{0}.{1}", t.Namespace, t.Name)
  59.  
  60.            If (excludedTypes.Count <> 0) Then
  61.                Debug.WriteLine(String.Format("    Excluded Enums:"))
  62.                For Each t As Type In excludedTypes
  63.                    Debug.WriteLine(String.Format("        '{0}.{1}' ({2})",
  64.                                                  t.Namespace, t.Name, Type.GetTypeCode(t).ToString))
  65.                Next t
  66.                Debug.WriteLine(String.Empty)
  67.            End If
  68.  
  69.            If (includedTypes.Count <> 0) Then
  70.                For Each t As Type In includedTypes
  71.                    Try
  72.                        Me.EvaluateEnumDuplicatedValues(t)
  73.  
  74.                    Catch ex As NotSupportedException
  75.                        Debug.WriteLine(String.Format("    Testing Enum '{0}.{1}' As {2}... IGNORED. NOT SUPPORTED.",
  76.                                                      t.Namespace, t.Name, Type.GetTypeCode(t).ToString()))
  77.  
  78.                    Catch ex As AssertFailedException
  79.                        Debug.WriteLine(String.Format("    Testing Enum '{0}.{1}' As {2} ({3} values)... TEST FAIL.",
  80.                                                      t.Namespace, t.Name, Type.GetTypeCode(t).ToString(), [Enum].GetValues(t).Length))
  81.  
  82.                        If (testException Is Nothing) Then
  83.                            testException = ex
  84.                            testFailed = True
  85.                        End If
  86.  
  87.                    Catch ex As Exception
  88.                        Debug.WriteLine(String.Format("    Testing Enum '{0}.{1}' As {2}... ERROR. EXCEPTION THROWN.",
  89.                                                      t.Namespace, t.Name, Type.GetTypeCode(t).ToString()))
  90.                        Debug.WriteLine("EXCEPTION MESSAGE:")
  91.                        Debug.WriteLine(ex.Message)
  92.                        Throw
  93.  
  94.                    End Try
  95.                Next t
  96.                Debug.WriteLine(String.Empty)
  97.            End If
  98.  
  99.            If (testFailed) Then
  100.                Throw testException
  101.            End If
  102.  
  103.        Next assName
  104.  
  105.    End Sub
  106.  
  107. #End Region
  108.  
  109. #Region " Private Methods "
  110.  
  111.    ''' <summary>
  112.    ''' Determines whether the definition of the source <see cref="[Enum]"/> contains duplicated values.
  113.    ''' </summary>
  114.    Private Sub EvaluateEnumDuplicatedValues(ByVal t As Type)
  115.  
  116.        Dim values As Array = [Enum].GetValues(t)
  117.        Dim valueCount As Integer = values.Length
  118.  
  119.        Dim repeatedValueNames As Object() =
  120.            (values.Cast(Of Object).GroupBy(Function(value As Object) value).
  121.                                    Where(Function(group As IGrouping(Of Object, Object)) group.Count > 1).
  122.                                    Select(Function(group As IGrouping(Of Object, Object)) group.Key)).ToArray()
  123.  
  124.        Dim repeatedValues As Long() = repeatedValueNames.Select(Function(x As Object) Convert.ToInt64(x)).ToArray()
  125.        Dim repeatedValueCount As Integer = repeatedValueNames.Count
  126.  
  127.        Dim formattedValues As New List(Of String)
  128.        For i As Integer = 0 To (repeatedValueNames.Length - 1)
  129.            formattedValues.Add(String.Format("{0}={1} (&H{2})",
  130.                                              repeatedValueNames(i), repeatedValues(i),
  131.                                              repeatedValues(i).ToString("X").TrimStart("F"c)))
  132.        Next
  133.  
  134.        Assert.AreEqual(0, repeatedValueCount,
  135.                        String.Format("Enum '{0}.{1}' has defined these duplicated values: {2}",
  136.                                      t.Namespace, t.Name, Environment.NewLine &
  137.                                      String.Join(Environment.NewLine, formattedValues)))
  138.  
  139.        Debug.WriteLine(String.Format("    Testing Enum '{0}.{1}' As {2} ({3} values)... Ok.",
  140.                                      t.Namespace, t.Name, Type.GetTypeCode(t).ToString(), valueCount))
  141.  
  142.    End Sub
  143.  
  144. #End Region
  145.  
  146. End Class


Resultado de Test Satisfactorio:

Citar
Test Name:  TestEnumDuplicatedValues
Test Outcome:   Passed
Result StandardOutput:  
Debug Trace:

Testing Assembly 'Elektro.Application.dll'...

    Testing Enum 'Elektro.Application.Data.Enums.SerializationType' As Int32 (3 values)... Ok
    Testing Enum 'Elektro.Application.Enums.ComparerResult' As Int32 (3 values)... Ok
    Testing Enum 'Elektro.Application.Enums.ProcessArchitecture' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.ControlHintType' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.FadingEffect' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.ListBoxItemSelectionState' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.RowMoveDirection' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.ScreenDockingPosition' As Int32 (9 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.SortModifiers' As Int32 (3 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.UndoRedoCheckBoxEvents' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.UndoRedoComboBoxEvents' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.UndoRedoCommand' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.UndoRedoDateTimePickerEvents' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.UndoRedoListBoxEvents' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.UndoRedoListViewEvents' As Int32 (3 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.UndoRedoMaskedTextBoxEvents' As Int32 (5 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.UndoRedoMonthCalendarEvents' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.UndoRedoNumericUpDownEvents' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.UndoRedoRichTextBoxEvents' As Int32 (5 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.UndoRedoTextBoxEvents' As Int32 (5 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.UndoRedoTextUpdateBehavior' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.WindowAnimation' As Int32 (20 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.WindowDockingPosition' As Int32 (12 values)... Ok
    Testing Enum 'Elektro.Application.UI.Enums.WindowEdges' As Int32 (9 values)... Ok

Testing Assembly 'Elektro.Core.dll'...

    Excluded Enums:
        'Elektro.Core.IO.Enums.DriveFileSystem' (Int32)
        'Elektro.Core.Maths.Types.Position' (Int32)

    Testing Enum 'Elektro.Core.Cryptography.Enums.HexadecimalStyle' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Core.DateAndTime.Enums.TimeMeasurerState' As Int32 (3 values)... Ok
    Testing Enum 'Elektro.Core.DateAndTime.Enums.TimeUnit' As Int32 (5 values)... Ok
    Testing Enum 'Elektro.Core.Generics.Enums.EnumFindDirection' As Int32 (5 values)... Ok
    Testing Enum 'Elektro.Core.IO.Enums.DateAttribute' As Int32 (4 values)... Ok
    Testing Enum 'Elektro.Core.IO.Enums.DeviceEvent' As Int32 (3 values)... Ok
    Testing Enum 'Elektro.Core.IO.Enums.DiscType' As Int64 (7 values)... Ok
    Testing Enum 'Elektro.Core.IO.Enums.DriveFormatResult' As Int32 (19 values)... Ok
    Testing Enum 'Elektro.Core.IO.Enums.HotkeyModifiers' As Int16 (6 values)... Ok
    Testing Enum 'Elektro.Core.IO.Enums.KeyBehavior' As Int32 (3 values)... Ok
    Testing Enum 'Elektro.Core.IO.Enums.MouseButton' As Int32 (9 values)... Ok
    Testing Enum 'Elektro.Core.IO.Enums.MouseWheelDirection' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Core.IO.Enums.ShortcutHotkeyModifier' As Int16 (5 values)... Ok
    Testing Enum 'Elektro.Core.IO.Enums.ShortcutWindowState' As Int32 (4 values)... Ok
    Testing Enum 'Elektro.Core.IO.Enums.SizeUnits' As Int64 (7 values)... Ok
    Testing Enum 'Elektro.Core.IO.Types.DeviceType' As Int32 (1 values)... Ok
    Testing Enum 'Elektro.Core.Maths.Enums.MetaCollectionType' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Core.Text.Enums.StringCase' As Int32 (13 values)... Ok
    Testing Enum 'Elektro.Core.Text.Enums.StringDirection' As Int32 (2 values)... Ok
    Testing Enum 'Elektro.Core.Text.Enums.TextDirection' As Int32 (2 values)... Ok

...


Reporte de Test Fallido:







UPDATE

Se me olvidó incluir la función GetLoadabletypes. Aquí la tienen:

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 18-December-2016
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Functions "
  9.  
  10. ' Assembly.GetLoadableTypes() As Type()
  11.  
  12. #End Region
  13.  
  14. #End Region
  15.  
  16. #Region " Option Statements "
  17.  
  18. Option Strict On
  19. Option Explicit On
  20. Option Infer Off
  21.  
  22. #End Region
  23.  
  24. #Region " Imports "
  25.  
  26. Imports System.ComponentModel
  27. Imports System.Reflection
  28. Imports System.Runtime.CompilerServices
  29.  
  30. #End Region
  31.  
  32. #Region " Assembly Extensions "
  33.  
  34. Namespace Extensions.[Assembly]
  35.  
  36.    ''' ----------------------------------------------------------------------------------------------------
  37.    ''' <summary>
  38.    ''' Contains custom extension methods to use with the <see cref="Global.System.Reflection.Assembly"/> type.
  39.    ''' </summary>
  40.    ''' ----------------------------------------------------------------------------------------------------
  41.    <HideModuleName>
  42.    Public Module Types
  43.  
  44. #Region " Public Extension Methods "
  45.  
  46.        ''' ----------------------------------------------------------------------------------------------------
  47.        ''' <summary>
  48.        ''' Gets the types defined in the specified a <see cref="Global.System.Reflection.Assembly"/>,
  49.        ''' only the types that can be loaded.
  50.        ''' <para></para>
  51.        ''' The types that cannot be loaded (eg. due to a missing 3rd party assembly reference) are not returned.
  52.        ''' </summary>
  53.        ''' ----------------------------------------------------------------------------------------------------
  54.        ''' <param name="sender">
  55.        ''' The source <see cref="Global.System.Reflection.Assembly"/>.
  56.        ''' </param>
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        ''' <returns>
  59.        ''' An array that contains all the types that are defined in this assembly, only the types that can be loaded.
  60.        ''' <para></para>
  61.        ''' The types that cannot be loaded (eg. Due to a missing 3rd party assembly reference) are not returned.
  62.        ''' </returns>
  63.        ''' ----------------------------------------------------------------------------------------------------
  64.        <DebuggerStepThrough>
  65.        <Extension>
  66.        <EditorBrowsable(EditorBrowsableState.Always)>
  67.        Public Function GetLoadableTypes(ByVal sender As Global.System.Reflection.Assembly) As Global.System.Type()
  68.  
  69.            Try
  70.                Return sender.GetTypes()
  71.  
  72.            Catch e As ReflectionTypeLoadException
  73.                Return (From t As Global.System.Type In e.Types
  74.                        Where (t IsNot Nothing) AndAlso (t.TypeInitializer IsNot Nothing)
  75.                        ).ToArray()
  76.  
  77.            End Try
  78.  
  79.        End Function
  80.  
  81. #End Region
  82.  
  83.    End Module
  84.  
  85. End Namespace
  86.  
  87. #End Region


« Última modificación: 9 Septiembre 2017, 06:38 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.813



Ver Perfil
Re: [SOURCE-CODE] Repositorio de tests de unidad y tests de integración para .NET
« Respuesta #2 en: 16 Diciembre 2016, 19:32 pm »

Test Para Descubrir Errores en Types IDisposable

El siguiente test, sirve para determinar si alguno de los types definidos en un ensamblado (los types que implementen la interfáz IDisposable) lanza alguna excepción  durante el proceso de instanciación y liberación.
El type debe tener un constructor sin parámetros para poder ser evaluado.

El test fallará en caso de que "X" type lance una excepción al momento de instanciarse o al momento de llamar al método Dispose para liberar sus recursos administrados y/o no administrados.

Este ejemplo lo he diseñado de tal forma que se pueda automatizar a gran escala, es un código reutilizable que se puede adaptar con el menor esfuerzo solo haciendo un copy&paste;
para ello he recurrido a Reflection, de esta manera podemos cargar los ensamblados referenciados que especifiquemos en un Array de tipo String(),
y obtener y evaluar todos los types visibles de dichos ensamblados.

Configuración Del Test:

Esta class nos servirá para mantener una referencia de los (nombres de) ensamblados que se evaluarán en el test.
Como es evidente, los ensamblados deberán estar referenciados en el proyecto de Unit Testing:


Código
  1. Public NotInheritable Class Fields
  2.  
  3.    ''' ----------------------------------------------------------------------------------------------------
  4.    ''' <summary>
  5.    ''' The referenced assembly names to test their members.
  6.    ''' </summary>
  7.    ''' ----------------------------------------------------------------------------------------------------
  8.    Public Shared ReadOnly AssemblyNames As String() = {
  9.        "Microsoft.VisualStudio.QualityTools.UnitTestFramework",
  10.        "..."
  11.    }
  12.  
  13.    Private Sub New()
  14.    End Sub
  15.  
  16. End Class


El Test:

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 16-December-2016
  4. ' ***********************************************************************
  5.  
  6. Option Strict On
  7. Option Explicit On
  8. Option Infer Off
  9.  
  10. Imports Microsoft.VisualStudio.TestTools.UnitTesting
  11. Imports System.Reflection
  12. Imports System.IO
  13.  
  14. ''' ----------------------------------------------------------------------------------------------------
  15. ''' <summary>
  16. ''' Tests for the <see cref="IDisposable"/> members defined in the assemblies of <see cref="Fields.AssemblyNames"/>.
  17. ''' </summary>
  18. ''' ----------------------------------------------------------------------------------------------------
  19. <TestClass()>
  20. Public NotInheritable Class TypeTests
  21.  
  22. #Region " Test Methods "
  23.  
  24.    ''' ----------------------------------------------------------------------------------------------------
  25.    ''' <summary>
  26.    ''' Performs a test on the <see cref="IDisposable"/> members defined in the assemblies of <see cref="Fields.AssemblyNames"/>,
  27.    ''' to evaluate the disposability of the <see cref="IDisposable"/> members.
  28.    ''' </summary>
  29.    ''' ----------------------------------------------------------------------------------------------------
  30.    <TestMethod()>
  31.    <TestCategory("Types")>
  32.    Public Sub TestIDisposableTypes()
  33.  
  34.        Dim testFailed As Boolean = False
  35.        Dim testException As AssertFailedException = Nothing
  36.  
  37.        ' Safe disposable types to exclude in this test.
  38.        ' -----------------------------------
  39.        ' These disposable types could throw an exception when disposed, however, are not considered a bug.
  40.        Dim excludedTypeNames As String() = {
  41.        }
  42.  
  43.        For Each assName As String In Fields.AssemblyNames
  44.  
  45.            Dim ass As Assembly = Assembly.Load(assName)
  46.            Debug.WriteLine(String.Format("Testing Assembly '{0}.dll'...", assName))
  47.            Debug.WriteLine(String.Empty)
  48.  
  49.            Dim excludedTypes As IEnumerable(Of Type) =
  50.                From t As Type In ass.GetTypes()
  51.                Where (t.GetInterfaces.Contains(GetType(IDisposable))) AndAlso (t.IsVisible)
  52.                Where excludedTypeNames.Contains(String.Format("{0}.{1}", t.Namespace, t.Name))
  53.                Order By String.Format("{0}.{1}", t.Namespace, t.Name)
  54.  
  55.            Dim includedTypes As IEnumerable(Of Type) =
  56.                From t As Type In ass.GetTypes()
  57.                Where (t.GetInterfaces.Contains(GetType(IDisposable))) AndAlso (t.IsVisible)
  58.                Where Not excludedTypeNames.Contains(String.Format("{0}.{1}", t.Namespace, t.Name))
  59.                Order By String.Format("{0}.{1}", t.Namespace, t.Name)
  60.  
  61.            If (excludedTypes.Count <> 0) Then
  62.                Debug.WriteLine(String.Format("    Excluded Disposable Types:"))
  63.                For Each t As Type In excludedTypes
  64.                    Debug.WriteLine(String.Format("        '{0}.{1}')", t.Namespace, t.Name))
  65.                Next t
  66.                Debug.WriteLine(String.Empty)
  67.            End If
  68.  
  69.            If (includedTypes.Count <> 0) Then
  70.                For Each t As Type In includedTypes
  71.                    Try
  72.                        Me.EvaluateDisposableType(t)
  73.  
  74.                    Catch ex As TargetInvocationException When (TypeOf ex.InnerException Is FileNotFoundException)
  75.                        Debug.WriteLine(String.Format("    Testing Disposable Type '{0}.{1}'... IGNORED. MISSING ASSEMBLY REFERENCE.", t.Namespace, t.Name))
  76.  
  77.                    Catch ex As FileNotFoundException
  78.                        Debug.WriteLine(String.Format("    Testing Disposable Type '{0}.{1}'... IGNORED. MISSING ASSEMBLY REFERENCE.", t.Namespace, t.Name))
  79.  
  80.                    Catch ex As MissingMethodException
  81.                        Debug.WriteLine(String.Format("    Testing Disposable Type '{0}.{1}'... IGNORED. NO PARAMETERLESS CONSTRUCTOR.", t.Namespace, t.Name))
  82.  
  83.                    Catch ex As ArgumentException
  84.                        Debug.WriteLine(String.Format("    Testing Disposable Type '{0}.{1}'... IGNORED. GENERIC PARAMETER REQUIRED.", t.Namespace, t.Name))
  85.  
  86.                    Catch ex As Exception
  87.                        Debug.WriteLine(String.Format("    Testing Disposable Type '{0}.{1}'... ERROR. EXCEPTION THROWN.", t.Namespace, t.Name))
  88.                        Debug.WriteLine("EXCEPTION MESSAGE:")
  89.                        Debug.WriteLine(ex.Message)
  90.                        Throw
  91.  
  92.                    End Try
  93.                Next t
  94.                Debug.WriteLine(String.Empty)
  95.            End If
  96.  
  97.            If (testFailed) Then
  98.                Throw testException
  99.            End If
  100.  
  101.        Next assName
  102.  
  103.    End Sub
  104.  
  105. #End Region
  106.  
  107. #Region " Private Methods "
  108.  
  109.    ''' ----------------------------------------------------------------------------------------------------
  110.    ''' <summary>
  111.    ''' Evaluates whether a disposable type throws an exception during instantiation and/or disposal operation.
  112.    ''' </summary>
  113.    ''' ----------------------------------------------------------------------------------------------------
  114.    ''' <param name="t">
  115.    ''' The source type.
  116.    ''' </param>
  117.    ''' ----------------------------------------------------------------------------------------------------
  118.    Private Sub EvaluateDisposableType(ByVal t As Type)
  119.  
  120.        Dim instance As IDisposable = DirectCast(Activator.CreateInstance(t), IDisposable)
  121.        instance.Dispose()
  122.        instance = Nothing
  123.  
  124.        Debug.WriteLine(String.Format("    Testing Disposable Type '{0}.{1}'... Ok", t.Namespace, t.Name))
  125.  
  126.    End Sub
  127.  
  128. #End Region
  129.  
  130. End Class


Resultado de Test Satisfactorio:

Citar
Test Name:  TestIDisposableTypes
Test Outcome:   Passed
Result StandardOutput:  
Debug Trace:

Testing Assembly 'Elektro.Application.dll'...

    Testing Disposable Type 'Elektro.Application.UI.Types.ControlDragger'... Ok
    Testing Disposable Type 'Elektro.Application.UI.Types.EditControlHook'... Ok
    Testing Disposable Type 'Elektro.Application.UI.Types.FormDragger'... Ok
    Testing Disposable Type 'Elektro.Application.UI.Types.UndoRedo`1'... IGNORED. GENERIC PARAMETER REQUIRED.

Testing Assembly 'Elektro.Imaging.dll'...

    Testing Disposable Type 'Elektro.Imaging.Types.ScreenRegionSelector'... Ok

Testing Assembly 'Elektro.Interop.dll'...

    Testing Disposable Type 'Elektro.Interop.Types.Compiler'... Ok
    Testing Disposable Type 'Elektro.Interop.Types.CompilerSettings'... Ok
    Testing Disposable Type 'Elektro.Interop.Types.CSharpCompiler'... IGNORED. NO PARAMETERLESS CONSTRUCTOR.
    Testing Disposable Type 'Elektro.Interop.Types.SafeBitmapHandle'... Ok
    Testing Disposable Type 'Elektro.Interop.Types.SafeCursorHandle'... Ok
    Testing Disposable Type 'Elektro.Interop.Types.SafeIconHandle'... Ok
    Testing Disposable Type 'Elektro.Interop.Types.SafeRegionHandle'... Ok
    Testing Disposable Type 'Elektro.Interop.Types.SafeWindowHandle'... Ok
    Testing Disposable Type 'Elektro.Interop.Types.VisualBasicCompiler'... IGNORED. NO PARAMETERLESS CONSTRUCTOR.
    Testing Disposable Type 'Elektro.Interop.Types.ZeroInvalidHandle'... IGNORED. NO PARAMETERLESS CONSTRUCTOR.

Testing Assembly 'Elektro.Multimedia.dll'...

    Testing Disposable Type 'Elektro.Multimedia.Types.AudioPlayer'... Ok
    Testing Disposable Type 'Elektro.Multimedia.Types.WaveRecorder'... Ok

Testing Assembly 'Elektro.Net.dll'...

    Testing Disposable Type 'Elektro.Net.Types.NetworkTrafficMonitor'... IGNORED. NO PARAMETERLESS CONSTRUCTOR.
    Testing Disposable Type 'Elektro.Net.Types.ProcessTrafficMonitor'... IGNORED. NO PARAMETERLESS CONSTRUCTOR.

Testing Assembly 'Elektro.Processes.dll'...

    Testing Disposable Type 'Elektro.Processes.Types.ProcessMonitor'... Ok
    Testing Disposable Type 'Elektro.Processes.Types.ProcessWatcher'... Ok

Testing Assembly 'Elektro.System.dll'...

    Testing Disposable Type 'Elektro.System.Types.PowerStateMonitor'... Ok


Reporte de Test Fallido:



Citar
Testing Assembly 'Elektro.Processes.dll'...

    Testing Disposable Type 'Elektro.Processes.Types.ProcessMonitor'... ERROR. EXCEPTION THROWN.
    EXCEPTION MESSAGE:
    Monitor is already stopped.
« Última modificación: 9 Septiembre 2017, 06:38 am por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Tests de velocidad y utilidades para nuestra conexión
Noticias
wolfbcn 2 4,012 Último mensaje 11 Mayo 2011, 10:28 am
por el-brujo
BuzzFeed usa sus tests para recolectar datos personales
Noticias
wolfbcn 0 1,167 Último mensaje 25 Junio 2014, 14:51 pm
por wolfbcn
Aparte de Enthuware hay mas programas para hacer tests de oracle 1Z0-851 ?
Java
Carlosjava 0 1,331 Último mensaje 31 Julio 2015, 17:07 pm
por Carlosjava
Programa para realizar tests 1Z0-851 aparte de Enthuware??
Java
Carlosjava 0 1,445 Último mensaje 7 Agosto 2015, 21:05 pm
por Carlosjava
tests para la seguridad
Seguridad
friend007 0 1,780 Último mensaje 4 Enero 2017, 06:39 am
por friend007
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines