doudichu1358 2018-06-02 05:49
浏览 398
已采纳

Golang中用于单元测试的种子随机数

I have functions that uses math/rand to "randomly" sample from a Poisson and another from the binomial distribution. It is often used by other functions that also return random values like h(g(f())) where f() g() and h() are random functions.

I placed a rand.Seed(n) call in main() to pick a different seed every time the program is run and it works fine.

My question is for unittests for these PRNG functions and the functions that use them using the builtin testing package. I would like to remove the randomness so that I can have a predictable value to compare with.

Where is the best place to place my constant value seed to get deterministic output? At the init() of the test file or inside every test function, or somewhere else?

  • 写回答

2条回答 默认 最新

  • dongqiang8683 2018-06-02 06:05
    关注

    You should certainly not put it in the test init() function. Why? Because execution order (or even if test functions are run) is non-deterministic. For details, see How to run golang tests sequentially?

    What does this mean?

    If you have 2 test functions (e.g. TestA() and TestB()) both of which test functions that call into math/rand, you don't have guarantees if TestA() is run first or TestB(), or even if any of those will be called. And so random data returned by math/rand will depend on this order.

    A better option would be to put seeding into TestA() and TestB(), but this may also be insufficient, as tests may run parallel, so the random data returned by math/rand may also be non-deterministic.

    To really have deterministic test results, functions that need random data would need to receive a math.Rand value and use that explicitly, and in tests you can create separate, distinct math.Rand values that will not be used by other tests, so seeding those to constant values and using those in the tested functions, only then can you have deterministic results that will not depend on how and in which order the test functions are called.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号