繁体   English   中英

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

[英]Elixir doctest fails for function that returns random values

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

当我运行我的测试时,我的 doctests 失败了。 生成的元组列表与我的 doctest 中定义的不同。 如何为返回随机值的函数编写 doctest?

您可以通过设置:rand的随机数生成器的种子来使随机函数具有确定性。 这也是在 Elixir 中测试Enum.random/1方式。

首先,打开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]

为了使用 doctests 测试函数,您必须能够预测函数的输出 在这种情况下,您无法预测函数的输出。


但是,您可以通过常规测试来测试您的功能。

这是一个测试,可以确保Color.pick_color()使用模式匹配生成 3 个元组的列表:

test "pick color" do
  [{_, _, _}, {_, _, _}, {_, _, _}] = Color.pick_color()
end

您还可以检查每个值是否在0255之间等。

暂无
暂无

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

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