Snippets

Nathaniel Knight Consistent, isolated, random UUID generator

Created by Nathaniel Knight last modified by unrecognized user

Independent Consistent Pseudo-Random UUID Generators

This module is a demonstration of how to generate sequences of pseudo random UUIDs using Python (and its standard library).

It has a couple of unit tests, which can be run as follows:

python -m unittest test
import random
import uuid


class RandomUuidGenerator:
    """Generates a sequence of pseudo-random UUIDs.

    Given the same seed, it will generate the same sequence.
    """

    def __init__(self, seed):
        self.rng = random.Random(seed)

    def gen_uuid(self):
        return uuid.UUID(
            bytes=bytes(self.rng.getrandbits(8) for _ in range(16)), version=4
        )
import random
import unittest

import generator

SEEDS = ["peanutbutter", "Elrond", "Sonic Screwdriver", 7, (192, 168, 0, 11)]


class TestRepeatedSequences(unittest.TestCase):

    SAMPLE_SIZE = 200

    def test_repeated_sequences(self):
        "Test that the same seed yields the same sequence."
        for seed in SEEDS:
            gen1 = generator.RandomUuidGenerator(seed)
            sample1 = [gen1.gen_uuid() for _ in range(self.SAMPLE_SIZE)]
            gen2 = generator.RandomUuidGenerator(seed)
            sample2 = [gen2.gen_uuid() for _ in range(self.SAMPLE_SIZE)]
            self.assertEqual(
                sample1,
                sample2,
                "Expected equal seeds to yield equal sequences",
            )


class TestInterleavedSequences(unittest.TestCase):

    SAMPLE_SIZE = 200

    def test_interleaved_draws_are_independent(self):
        "Check that two generators can co-exist without interferce."
        for seed in SEEDS:
            generators = {
                "left": generator.RandomUuidGenerator(seed),
                "right": generator.RandomUuidGenerator(seed),
            }
            results = {"left": [], "right": []}
            directions = ["left" for _ in range(self.SAMPLE_SIZE)]
            directions.extend("right" for _ in range(self.SAMPLE_SIZE))
            random.shuffle(directions)
            for d in directions:
                gen = generators[d]
                drawn = gen.gen_uuid()
                results[d].append(drawn)
            self.assertEqual(results["left"], results["right"])

Comments (0)