import random


def _limitsample(sample, desiredlen, randomize=True):
    """return a random subset of sample of at most desiredlen item.

    If randomize is False, though, a deterministic subset is returned.
    This is meant for integration tests.
    """
    if len(sample) <= desiredlen:
        return sample
    if randomize:
        return set(random.sample(sample, desiredlen))
    sample = list(sample)
    sample.sort()
    return set(sample[:desiredlen])