简体   繁体   English

学习F#:是否可以创建一个测试用例来验证签名?

[英]Learning F#: Is it possible to create a test case to verify a signature?

With unit-testing several hundred lines of F# code I realized that it would be advantageous to not only check the output but also the signatures. 通过对几百行F#代码进行单元测试,我意识到不仅要检查输出而且要检查签名是有利的。 The reason being if the code is validated for a release and then changes are made after the release that modify the signature, one would want to know why the signature changed so that either the test case can be updated for the new signature or to flag the change as causing a problem. 原因是如果代码被验证用于发布,然后在修改签名的发布之后进行更改,则可能想知道签名更改的原因,以便可以为新签名更新测试用例或标记改变导致问题。

Is it possible to create a test case to verify a signature? 是否可以创建一个测试用例来验证签名? If so, how? 如果是这样,怎么样?

I think the best approach would be to simply provide test cases which cover the bounds of your signature. 我认为最好的方法是简单地提供涵盖签名范围的测试用例。 eg, to verify that a return type is an int , 例如,要验证返回类型是否为int

let x:int = someFunc() //you'll get a compiler error if the return type changes

Really, I'd expect that just by virtue of exhaustively testing your public API, you will have necessarily tested the signatures. 实际上,我希望通过详尽地测试您的公共API,您必须测试签名。 Especially in a language like F#, which has a relatively strict static type system. 尤其是像F#这样的语言,它具有相对严格的静态类型系统。

I suppose you could also venture to use reflection to assert signatures, but honestly I don't think that would be such a good investment of time. 我想你也可以冒险使用反射来断言签名,但说实话,我认为这不会是一次如此好的时间投入。

As said by Stephen, if you write some unit tests for your code, the unit tests will generally call the function with values of the type that the function require, so that will automatically also check the signature (if you change the signature, you will not be able to compile your tests). 正如斯蒂芬所说,如果你为你的代码编写了一些单元测试,单元测试通常会调用函数所需类型值的函数,这样就会自动检查签名(如果更改签名,你会无法编译您的测试)。

Another alternative, which is suitable for libraries is to use F# interface files ( .fsi ). 另一种适用于库的替代方法是使用F#接口文件( .fsi )。 The interface file specifies types of public functions in the implementation file ( .fs ) and it is also a good place for documentation. 接口文件指定实现文件( .fs )中的公共函数类型,它也是文档的好地方。

If you then (accidentally) change the type of your implementation, your code will not compile unless you update the type in the interface file. 如果您(不小心)更改了实现的类型,除非您更新接口文件中的类型,否则您的代码将无法编译。

You will probably want to maintain the interface file by hand (see F# library sources for a good example), but you can get an initial by calling the compiler with --sig:mylibrary.fsi . 您可能希望手动维护接口文件(请参阅F#库源以获得一个很好的示例),但您可以通过使用--sig:mylibrary.fsi调用编译器来--sig:mylibrary.fsi You could probaby use this switch to automate the testing (and check the diff between signature files after each compilation). 您可以使用此开关自动执行测试(并在每次编译后检查签名文件之间的差异)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM