返回随机值的函数的 Elixir doctest 失败

标签 elixir ex-unit

我在 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/

相关文章:

elixir - 自定义 ExUnit 断言和模式匹配

functional-programming - 在 elixir 中使用带有过滤器和映射的管道

elixir - 如何测试 Ecto 迁移

dependencies - Elixir 依赖项中的版本

conditional-statements - Elixir 中 cond block 中条件内的绑定(bind)表达式?

elixir - ExUnit - 如何通过命名设置函数将上下文传递到描述 block 中的测试宏

elixir - ExUnit 断言

testing - Elixir 中的测试方法委托(delegate)

elixir - 在 Elixir(非 Phoenix)应用程序中渲染部分 EEx 模板

elixir - Elixir中的串联数组