Comparison of Discriminative Unions

I am new to F # and I play with FParsec. I would use FParsec to generate an AST. I would like to use FsUnit to write some tests around various parts of the analyzer to ensure proper operation.

I am having problems with the syntax (sorry, the exact code works, I can publish a specific example later), since it is precisely possible to compare two discriminatory unions (one of them is expected, the other is the actual result)? Can someone provide a small code example using FsUnit (or NUnit), please?

Example of discriminated union (very simple)

type AST = | Variable of string | Class of string | Number of int 
+5
source share
2 answers

Since, as Brian remarked, F # unions have structural equality, this is easy to use considering which unit testing module you like.

FsUnit is a special F # library built on top of NUnit. My personal favorite F # unit testing library is Unquote,; ), which is an agnostic framework, works very well with NUnit, xUnit.net, MbUnit, ... or even inside FSI. You may be interested in this comparison with FsUnit.

So how would you do this with NUnit + Unquote? Here is a complete working example:

 module UnitTests open NUnit.Framework open Swensen.Unquote type AST = | Variable of string | Class of string | Number of int let mockFParsec_parseVariable input = Variable(input) [<Test>] let ``test variable parse, passing example`` () = test <@ mockFParsec_parseVariable "x" = Variable("x") @> [<Test>] let ``test variable parse, failing example`` () = test <@ mockFParsec_parseVariable "y" = Variable("x") @> 

Then, by running tests using TestDriven.NET, the output is as follows:

 ------ Test started: Assembly: xxx.exe ------ Test 'UnitTests.test variable parse, failing example' failed: UnitTests.mockFParsec_parseVariable "y" = Variable("x") Variable "y" = Variable("x") false C:\xxx\UnitTests.fs(19,0): at UnitTests.test variable parse, failing example() 1 passed, 1 failed, 0 skipped, took 0.80 seconds (NUnit 2.5.10). 
+6
source

Example - if you want to check the type, but not the content

 let matched x= match x with |Variable(_) -> true | _ -> false 

Note that you need a different function for each element of the delimited union

If you want to compare equality, you can just do it in a standard way, for example

 Assert.AreEqual(Variable("hello"),result) 

or

 if result = Variable("hello") then stuff() 
+2
source

Source: https://habr.com/ru/post/954584/


All Articles