Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Hedgehog.sln
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hedgehog.Xunit.Tests.CSharp
EndProject
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Hedgehog.Xunit.Tests.FSharp", "tests\Hedgehog.Xunit.Tests.FSharp\Hedgehog.Xunit.Tests.FSharp.fsproj", "{856960BF-6CD8-4BBB-949F-02A47BCF8EC7}"
EndProject
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Hedgehog.NUnit", "src\Hedgehog.NUnit\Hedgehog.NUnit.fsproj", "{4F1FFCB9-BA0A-432A-97F0-D302DE1348BD}"
EndProject
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Hedgehog.NUnit.Tests.FSharp", "tests\Hedgehog.NUnit.Tests.FSharp\Hedgehog.NUnit.Tests.FSharp.fsproj", "{70CB049A-FA03-4361-914A-8D2F4D291062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -77,6 +81,14 @@ Global
{856960BF-6CD8-4BBB-949F-02A47BCF8EC7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{856960BF-6CD8-4BBB-949F-02A47BCF8EC7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{856960BF-6CD8-4BBB-949F-02A47BCF8EC7}.Release|Any CPU.Build.0 = Release|Any CPU
{4F1FFCB9-BA0A-432A-97F0-D302DE1348BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4F1FFCB9-BA0A-432A-97F0-D302DE1348BD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4F1FFCB9-BA0A-432A-97F0-D302DE1348BD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4F1FFCB9-BA0A-432A-97F0-D302DE1348BD}.Release|Any CPU.Build.0 = Release|Any CPU
{70CB049A-FA03-4361-914A-8D2F4D291062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{70CB049A-FA03-4361-914A-8D2F4D291062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{70CB049A-FA03-4361-914A-8D2F4D291062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{70CB049A-FA03-4361-914A-8D2F4D291062}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -95,5 +107,7 @@ Global
{C7D1E5C7-0281-4752-A7C7-E0C2CB2EF13D} = {3C2CF07C-905B-4162-BE81-46060153841B}
{1E243C1E-563C-4D59-A270-9CB68B578540} = {ED87B4D7-BBFF-4B2A-A924-91939E5C3F00}
{856960BF-6CD8-4BBB-949F-02A47BCF8EC7} = {ED87B4D7-BBFF-4B2A-A924-91939E5C3F00}
{4F1FFCB9-BA0A-432A-97F0-D302DE1348BD} = {3C2CF07C-905B-4162-BE81-46060153841B}
{70CB049A-FA03-4361-914A-8D2F4D291062} = {ED87B4D7-BBFF-4B2A-A924-91939E5C3F00}
EndGlobalSection
EndGlobal
34 changes: 34 additions & 0 deletions src/Hedgehog.NUnit/AutoGenConfig.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
namespace Hedgehog.NUnit

open System
open Hedgehog

module internal AutoGenConfig =
let instantiate (configType: Type) (configArgs: obj array) =
Comment thread
AlexeyRaga marked this conversation as resolved.
let configArgs = configArgs |> Option.ofObj |> Option.defaultValue [||]

configType.GetMethods()
|> Seq.filter (fun p -> p.IsStatic && p.ReturnType = typeof<IAutoGenConfig>)
|> Seq.seqTryExactlyOne
|> Option.requireSome
$"%s{configType.FullName} must have exactly one public static property that returns an AutoGenConfig.

An example type definition:

type %s{configType.Name} =
static member __ =
AutoGenConfig.defaults |> AutoGenConfig.addGenerator (Gen.constant 13)
"
|> fun methodInfo ->
let methodInfo =
if methodInfo.IsGenericMethod then
methodInfo.GetParameters()
|> Array.map _.ParameterType.IsGenericParameter
|> Array.zip configArgs
|> Array.filter snd
|> Array.map (fun (arg, _) -> arg.GetType())
|> fun argTypes -> methodInfo.MakeGenericMethod argTypes
else
methodInfo

methodInfo.Invoke(null, configArgs) :?> IAutoGenConfig
182 changes: 182 additions & 0 deletions src/Hedgehog.NUnit/GenAttribute.Prelude.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
namespace Hedgehog.NUnit

open System
open Hedgehog
open Hedgehog.FSharp

[<AutoOpen>]
module private RangeHelpers =

[<Literal>]
let private LargeRangeThreshold = 1000L
[<Literal>]
let private MediumRangeThreshold = 100L

/// Choose between constant, linear, and exponential range based on the range size.
/// - For ranges > 1000: use exponential to ensure boundary values are tested
/// - For ranges > 100: use linear for balanced shrinking
/// - For ranges <= 100: use constant (no shrinking needed for small ranges)
let inline chooseRangeInt32 (min: int) (max: int) : Range<int> =
let rangeSize = int64 max - int64 min
let origin = if min <= 0 && 0 <= max then 0 else min
match rangeSize with
Comment thread
AlexeyRaga marked this conversation as resolved.
| size when size > LargeRangeThreshold -> Range.exponentialFrom origin min max
| size when size > MediumRangeThreshold -> Range.linearFrom origin min max
| _ -> Range.constantFrom origin min max

/// <summary>Generates an integer within a specified range.</summary>
/// <remarks>Range strategy: exponential (>1000), linear (>100), or constant (≤100).</remarks>
type IntAttribute(min: int, max: int) =
inherit GenAttribute<int>()
/// <summary>Generates an integer from Int32.MinValue to Int32.MaxValue.</summary>
/// <remarks>Range strategy: exponential (>1000), linear (>100), or constant (≤100).</remarks>
new() = IntAttribute(Int32.MinValue, Int32.MaxValue)
override _.Generator =
Gen.int32 (chooseRangeInt32 min max)

/// <summary>Generates an odd integer.</summary>
/// <remarks>Range strategy: exponential (>1000), linear (>100), or constant (≤100).</remarks>
type OddAttribute(min: int, max: int) =
inherit GenAttribute<int>()
/// <summary>Generates an odd integer from Int32.MinValue to Int32.MaxValue.</summary>
/// <remarks>Range strategy: exponential (>1000), linear (>100), or constant (≤100).</remarks>
new() = OddAttribute(Int32.MinValue, Int32.MaxValue)
override _.Generator = gen {
let! n = Gen.int32 (chooseRangeInt32 min max)
return n ||| 1
}

/// <summary>Generates an even integer.</summary>
/// <remarks>Range strategy: exponential (>1000), linear (>100), or constant (≤100).</remarks>
type EvenAttribute(min: int, max: int) =
inherit GenAttribute<int>()
/// <summary>Generates an even integer from Int32.MinValue to Int32.MaxValue.</summary>
/// <remarks>Range strategy: exponential (>1000), linear (>100), or constant (≤100).</remarks>
new() = EvenAttribute(Int32.MinValue, Int32.MaxValue)
override _.Generator = gen {
let! n = Gen.int32 (chooseRangeInt32 min max)
return n &&& ~~~1
}

/// <summary>Generates a positive integer.</summary>
/// <remarks>Range strategy: exponential (>1000), linear (>100), or constant (≤100).</remarks>
type PositiveIntAttribute(max: int) =
inherit GenAttribute<int>()
/// <summary>Generates a positive integer from 1 to Int32.MaxValue.</summary>
/// <remarks>Range strategy: exponential (>1000), linear (>100), or constant (≤100).</remarks>
new() = PositiveIntAttribute(Int32.MaxValue)
override _.Generator =
Gen.int32 (chooseRangeInt32 1 max)

/// <summary>Generates a non-negative integer.</summary>
/// <remarks>Range strategy: exponential (>1000), linear (>100), or constant (≤100).</remarks>
type NonNegativeIntAttribute(max: int) =
inherit GenAttribute<int>()
/// <summary>Generates a non-negative integer from 0 to Int32.MaxValue.</summary>
/// <remarks>Range strategy: exponential (>1000), linear (>100), or constant (≤100).</remarks>
new() = NonNegativeIntAttribute(Int32.MaxValue)
override _.Generator =
Gen.int32 (chooseRangeInt32 0 max)

/// <summary>Generates a non-zero integer.</summary>
/// <remarks>Range strategy: exponential (>1000), linear (>100), or constant (≤100).</remarks>
type NonZeroIntAttribute(min: int, max: int) =
inherit GenAttribute<int>()
/// <summary>Generates a non-zero integer from Int32.MinValue+1 to Int32.MaxValue.</summary>
/// <remarks>Range strategy: exponential (>1000), linear (>100), or constant (≤100).</remarks>
new() = NonZeroIntAttribute(Int32.MinValue + 1, Int32.MaxValue)
override _.Generator =
match min, max with
| _, m when m < 0 -> Gen.int32 (chooseRangeInt32 min max) // Range entirely negative
| n, _ when n > 0 -> Gen.int32 (chooseRangeInt32 min max) // Range entirely positive
| n, m -> // 0 is in range, split it
Gen.choice [
Gen.int32 (chooseRangeInt32 n -1)
Gen.int32 (chooseRangeInt32 1 m)
]

/// Generates a string that is a valid identifier.
type IdentifierAttribute(maxLen: int) =
inherit GenAttribute<string>()
new() = IdentifierAttribute(25)
override _.Generator =
Gen.identifier maxLen

/// Generates a string representing a Latin name.
type LatinNameAttribute(maxLength: int) =
inherit GenAttribute<string>()
new() = LatinNameAttribute(20)
override _.Generator =
Gen.latinName maxLength

/// Generates a string in snake_case.
type SnakeCaseAttribute(maxWordLength: int, maxWordsCount: int) =
inherit GenAttribute<string>()
new() = SnakeCaseAttribute(5, 5)
override _.Generator =
Gen.snakeCase (Range.constant 1 maxWordLength) (Range.constant 1 maxWordsCount)

/// Generates a string in kebab-case.
type KebabCaseAttribute(maxWordLength: int, maxWordsCount: int) =
inherit GenAttribute<string>()
new() = KebabCaseAttribute(5, 5)
override _.Generator =
Gen.kebabCase (Range.constant 1 maxWordLength) (Range.constant 1 maxWordsCount)

/// Generates a valid domain name.
type DomainNameAttribute() =
inherit GenAttribute<string>()
override _.Generator =
Gen.domainName

/// Generates a valid email address.
type EmailAttribute() =
inherit GenAttribute<string>()
override _.Generator =
Gen.email

/// Generates a DateTime value.
type DateTimeAttribute(kind: DateTimeKind, from: DateTime, duration: TimeSpan) =
inherit GenAttribute<DateTime>()
new() = DateTimeAttribute(DateTimeKind.Utc, DateTime(2000, 1, 1), TimeSpan.FromDays(3650))
new(from, duration) = DateTimeAttribute(DateTimeKind.Utc, from, duration)
new(kind) = DateTimeAttribute(kind, DateTime(2000, 1, 1), TimeSpan.FromDays(3650))
override _.Generator =
Gen.dateTime (Range.constant from (from + duration))
|> Gen.map (fun x -> DateTime.SpecifyKind(x, kind))

/// Generates a DateTimeOffset value.
type DateTimeOffsetAttribute(from: DateTimeOffset, duration: TimeSpan) =
inherit GenAttribute<DateTimeOffset>()
new() = DateTimeOffsetAttribute(DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero), TimeSpan.FromDays(3650))
new(from) = DateTimeOffsetAttribute(from, TimeSpan.FromDays(3650))
override _.Generator =
Gen.dateTimeOffset (Range.constant from (from + duration))

/// Generates a string containing alphanumeric characters.
type AlphaNumStringAttribute(minLength: int, maxLength: int) =
inherit GenAttribute<string>()
new() = AlphaNumStringAttribute(0, 256)
new(minLength) = AlphaNumStringAttribute(minLength, 256)
override _.Generator =
Gen.string (Range.constant minLength maxLength) Gen.alphaNum

/// Generates a string containing unicode characters.
type UnicodeStringAttribute(minLength: int, maxLength: int) =
inherit GenAttribute<string>()
new() = UnicodeStringAttribute(0, 256)
new(minLength) = UnicodeStringAttribute(minLength, 256)
override _.Generator =
Gen.string (Range.constant minLength maxLength) Gen.unicode

/// Generates an IP address (IPv4).
type Ipv4AddressAttribute() =
inherit GenAttribute<System.Net.IPAddress>()
override _.Generator =
Gen.ipv4Address

/// Generates an IPv6 address.
type Ipv6AddressAttribute() =
inherit GenAttribute<System.Net.IPAddress>()
override _.Generator =
Gen.ipv6Address
28 changes: 28 additions & 0 deletions src/Hedgehog.NUnit/GenAttribute.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
namespace Hedgehog.NUnit

open System
open Hedgehog
open Hedgehog.FSharp

/// Set a Generator for a parameter of a test annotated with `Property`
///
/// Example usage:
///
/// ```
///
/// type ConstantInt(i: int) =
/// inherit GenAttribute<int>()
/// override _.Generator = Gen.constant i
///
/// [<Property>]
/// let ``is always 2`` ([<ConstantInt(2)>] i) =
/// Assert.AreEqual(2, i)
///
/// ```
[<AbstractClass>]
[<AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)>]
type GenAttribute<'a>() =
inherit Attribute()

abstract member Generator: Gen<'a>
member this.Box() = this.Generator |> Gen.map box
61 changes: 61 additions & 0 deletions src/Hedgehog.NUnit/Hedgehog.NUnit.fsproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<IsPackable>true</IsPackable>
<TargetFramework>net8.0</TargetFramework>
<Version>1.0.0</Version>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<DebugType>Embedded</DebugType>
<EmbedAllSources>True</EmbedAllSources>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
<Description>Hedgehog with batteries for NUnit included.</Description>
<Authors>Alexey Raga</Authors>
<PackageProjectUrl>https://hedgehogqa.github.io/fsharp-hedgehog</PackageProjectUrl>
<PackageTags>f# fsharp c# csharp testing nunit</PackageTags>
<PackageIcon>hedgehog-logo.png</PackageIcon>
<PackageId>Hedgehog.NUnit</PackageId>
<PackageDescription>
Hedgehog with convenience attributes for NUnit.

- Test method arguments generated with a custom Gen.auto...
- ...or with a custom Generator.
- Property.check called for each test.
</PackageDescription>
<RootNamespace>Hedgehog.NUnit</RootNamespace>
</PropertyGroup>

<ItemGroup>
<InternalsVisibleTo Include="Hedgehog.NUnit.Tests.FSharp" />
</ItemGroup>

<ItemGroup>
<Compile Include="Prelude.fs" />
<Compile Include="AutoGenConfig.fs" />
<Compile Include="IPropertyAttribute.fs" />
<Compile Include="RecheckAttribute.fs" />
<Compile Include="GenAttribute.fs" />
<Compile Include="GenAttribute.Prelude.fs" />
<Compile Include="PropertyContext.fs" />
<Compile Include="ReflectionHelpers.fs" />
<Compile Include="InternalLogic.fs" />
<Compile Include="PropertyAttribute.fs" />
<Compile Include="PropertiesAttribute.fs" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Hedgehog\Hedgehog.fsproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="NUnit" Version="4.4.0" />
</ItemGroup>

<ItemGroup>
<None Include="..\..\img\hedgehog-logo.png" Pack="true" PackagePath="\" Visible="false" />
<None Include="..\..\LICENSE" Pack="true" PackagePath="\" Visible="false" />
<None Include="..\..\README.md" Pack="true" PackagePath="\" Visible="false" />
</ItemGroup>

</Project>
14 changes: 14 additions & 0 deletions src/Hedgehog.NUnit/IPropertyAttribute.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace Hedgehog.NUnit

open System
open Hedgehog

// Represents the interface for property attributes used in property-based testing.
// This interface is shared between Property and Properties attributes.
[<Interface>]
type internal IPropertyAttribute =
abstract member AutoGenConfig: Type option with get, set
abstract member AutoGenConfigArgs: obj array with get, set
abstract member Tests: int<tests> option with get, set
abstract member Shrinks: int<shrinks> option with get, set
abstract member Size: Size option with get, set
Loading
Loading