我在 Elixir 中有一个函数可以在列表中生成三个随机 RGB 元组。
defmodule Color do
@doc """
Create three random r,g,b colors as a list of three tuples
## Examples
iex> colors = Color.pick_color()
iex> colors
[{207, 127, 117}, {219, 121, 237}, {109, 101, 206}]
"""
def pick_color() do
color = Enum.map((0..2), fn(x)->
r = Enum.random(0..255)
g = Enum.random(0..255)
b = Enum.random(0..255)
{r, g, b}
end)
end
当我运行测试时,我的文档测试失败了。生成的元组列表与我的 doctest 中定义的不同。如何为返回随机值的函数编写 doctest?
最佳答案
您可以通过设置 :rand
的种子来使随机函数具有确定性的随机数生成器。 This is also how Enum.random/1
is tested in Elixir.
首先打开iex
并将当前进程的种子设置为任意值:
iex> :rand.seed(:exsplus, {101, 102, 103})
然后,在 iex
中运行您的函数
iex> Color.pick_color()
现在只需将此值与 :rand.seed
一起复制到您的 doctest 中称呼。通过显式设置种子,您将从 :rand
中的函数获得相同的值。模块和 Enum.random/1
使用 :rand
内部。
iex(1)> :rand.seed(:exsplus, {1, 2, 3})
iex(2)> for _ <- 1..10, do: Enum.random(1..10)
[4, 3, 8, 1, 6, 8, 1, 6, 7, 7]
iex(3)> :rand.seed(:exsplus, {1, 2, 3})
iex(4)> for _ <- 1..10, do: Enum.random(1..10)
[4, 3, 8, 1, 6, 8, 1, 6, 7, 7]
iex(5)> :rand.seed(:exsplus, {1, 2, 3})
iex(6)> for _ <- 1..10, do: Enum.random(1..10)
[4, 3, 8, 1, 6, 8, 1, 6, 7, 7]
关于返回随机值的函数的 Elixir doctest 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48857468/