Background
I want to test my code which depends on random
module.
The problem
Since random
module produces pseudo-random numbers, I always set random.seed(X)
to known value X
. This works for consecutive test runs. However, Python 3 seems to give different numbers than Python 2 when using random.choice([D, C])
Following snippet:
import random
random.seed(1)
for i in random(10):
print(random.choice(['C', 'D']), end=', ')
gives different result for Python 2 and 3
$ python2 test.py
C, D, D, C, C, C, D, D, C, C
$ python3 test.py
C, C, D, C, D, D, D, D, C, C
However, random.random
method works the same on 2.x and 3.x:
import random
random.seed(1)
for i in random(10):
print(random.random())
$ python3 test.py
0.13436424411240122
0.8474337369372327
0.763774618976614
0.2550690257394217
0.49543508709194095
0.4494910647887381
0.651592972722763
0.7887233511355132
0.0938595867742349
0.02834747652200631
$ python2 test.py
0.134364244112
0.847433736937
0.763774618977
0.255069025739
0.495435087092
0.449491064789
0.651592972723
0.788723351136
0.0938595867742
0.028347476522
Workaround
I can mock
the output of random.choice
, which works well for simple test cases. However, for fairly complicated test cases, I'm not able to mock output, because I simply don't know how it should look like.
The question
Have I done something wrong when calling random.choice
method?
Aucun commentaire:
Enregistrer un commentaire