[英]Doctesting a function that returns different map during every run
Let's say that my function returns a map and some of the value may be randomly generated. 假设我的函数返回了一个映射,某些值可能是随机生成的。 I'd like to be able to at least test again output type, or in another words - to check from the doctest level weather returned value is a map. 我希望至少能够再次测试输出类型,或者换句话说-从doctest级别检查天气返回的值是否是地图。 Eventually does it contains specific keys. 最终它是否包含特定的键。 Is it even possible? 可能吗? The function call may look following: 该函数调用可能如下所示:
iex> MyApp.function(params, opts)
%{_}
The output can't be a pattern, but you can either use is_map
or the match?
输出不能是模式,但是可以使用is_map
或match?
macro with the pattern %{}
, both of which will return true
if the value is a map. 格式为%{}
宏,如果该值为地图,则两者都将返回true
。
iex> is_map MyApp.function(params, opts)
true
iex> match? %{}, MyApp.function(params, opts)
true
While answer by @Dogbert is perfectly correct, it could not be used in all cases. 尽管@Dogbert的回答是完全正确的,但并非在所有情况下都可以使用它。 When one needs to check a value that is unpredictable in advance (say, randomly generated,) there is still an ability to do that with ExUnit
. 当需要预先检查一个不可预测的值(例如,随机生成)时,仍然可以使用ExUnit
。
Each run of test suite prints out the Random seed value as the very last line of test run: 每次测试套件运行都将随机种子值打印出来,作为测试运行的最后一行:
Randomized with seed 486290
It might be recorded and passed back to ExUnit.configure/1
. 它可能会被记录并传递回ExUnit.configure/1
。 In such a case, random value returned from the function will be the same (it will not change between different runs.) 在这种情况下,从函数返回的随机值将是相同的(在不同的运行之间不会改变)。
This trick won't work for data, received from third-party services, of course. 当然,此技巧不适用于从第三方服务接收的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.