Elixir doctest对于返回随机值的函数失败 [英] Elixir doctest fails for function that returns random values

查看:96
本文介绍了Elixir doctest对于返回随机值的函数失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Elixir中有一个函数,该函数在列表中生成三个随机RGB元组。

I have a function in Elixir that produces three random RGB tuples in a list.

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?

When I run my tests, my doctests fail. The resulting list of tuples are different than what is defined in my doctest. How can I write a doctest for a function that returns a random value?

推荐答案

要使用doctest测试功能,您必须能够预测功能的输出。在这种情况下,您将无法预测函数的输出。

In order to test a function with doctests, you must be able to predict the output of your function. In this case, you can't predict the output of your function.

但是您可以使用常规测试来测试函数。

However you could test your function with regular tests.

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

Here is a test that would make sure Color.pick_color() produces a list of 3 tuples, using pattern matching:

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

您还可以检查每个值是否在 0 255 等。

You could also check if each value is between 0 and 255, etc.

这篇关于Elixir doctest对于返回随机值的函数失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆