On 4/15/14 11:54 AM, Nick Mellor wrote:
Hi guys,

(Python 2.7, Windows 7 64-bit)

Here's a bit of code stress-testing a method addUpdate_special_to_cart. The test adds and 
updates random "specials" (multiple products bundled at an advantageous price) 
of various sizes to thousands of shopping carts, then restocks the whole darn lot. The 
test passes if the stock level afterwards is the same as it was before executing the code 
for all products.

addUpdate_special_to_cart is working perfectly. But the test isn't.

The test iterates over the same code twice, once with special_qty==4, once with 
special_qty==0, reseeding the Python random module number generator to a fixed 
seed (a string) between the iterations. special_qty==0 removes the special and 
restocks the products. The test relies on precisely the same random number 
sequence on both runs.

Can you think of a reason why the random number generator should fall out of sync between 
the two iterations? Because that's what's happening by the look of it: occasionally 
products are returned to the wrong stockbin. No "random" module method is used 
anywhere else while this code is executing.

When I assign something non-random to the stockbin parameter, the test passes.

Best wishes,



Nick

for qty in [4, 0]:
                 random.seed(seed)
                 for cart in range(test_size):
                     for special in range(randrange(3)):
                         s.addUpdate_special_to_cart(cart=cart, 
stockbin=randrange(test_size),
                                                     
special_id=randrange(test_size), special_qty=qty,
                                                     
products=[(random.choice(PRODUCTS), random.choice(range(10)))
                                                         for r in 
range(randrange(7))])


The best way to ensure repeatability of random numbers is to avoid the module-level functions, and instead create your own random.Random() instance to generate numbers. Then you can be certain it isn't being used by anything else.

--
Ned Batchelder, http://nedbatchelder.com

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to