Example #1
0
def _tensor_splits(draw):
    lengths = draw(st.lists(st.integers(1, 5), min_size=1, max_size=10))
    batch_size = draw(st.integers(1, 5))
    element_pairs = [
        (batch, r) for batch in range(batch_size) for r in range(len(lengths))
    ]
    perm = draw(st.permutations(element_pairs))
    perm = perm[:-1]  # skip one range
    ranges = [[(0, 0)] * len(lengths) for _ in range(batch_size)]
    offset = 0
    for pair in perm:
        ranges[pair[0]][pair[1]] = (offset, lengths[pair[1]])
        offset += lengths[pair[1]]

    data = draw(st.lists(
        st.floats(min_value=-1.0, max_value=1.0),
        min_size=offset,
        max_size=offset
    ))

    key = draw(st.permutations(range(offset)))

    return (
        np.array(data).astype(np.float32), np.array(ranges),
        np.array(lengths), np.array(key).astype(np.int64)
    )
Example #2
0
def _tensor_splits(draw):
    lengths = draw(st.lists(st.integers(1, 5), min_size=1, max_size=10))
    batch_size = draw(st.integers(1, 5))
    element_pairs = [
        (batch, r) for batch in range(batch_size) for r in range(len(lengths))
    ]
    perm = draw(st.permutations(element_pairs))
    perm = perm[:-1]  # skip one range
    ranges = [[(0, 0)] * len(lengths) for _ in range(batch_size)]
    offset = 0
    for pair in perm:
        ranges[pair[0]][pair[1]] = (offset, lengths[pair[1]])
        offset += lengths[pair[1]]

    data = draw(st.lists(
        st.floats(min_value=-1.0, max_value=1.0),
        min_size=offset,
        max_size=offset
    ))

    key = draw(st.permutations(range(offset)))

    return (
        np.array(data).astype(np.float32), np.array(ranges),
        np.array(lengths), np.array(key).astype(np.int64)
    )
Example #3
0
def test_stack(data, x):
    perm = data.draw(permutations(x.dims))
    print(perm)
    y = x.transpose(*perm)
    n = data.draw(name(x))
    z = ntorch.stack([x, y], n)
    assert set(z.dims) == set(x.dims) | set([n])
def python(draw):
    interesting = draw(st.lists(composite_statement, min_size=1))
    boring = draw(st.lists(statement, min_size=0))
    padding_lines = [""] * draw(st.integers(0, 100))
    return ("\n".join(
        draw(st.permutations(interesting + boring + padding_lines))).strip() +
            "\n")
Example #5
0
def complete_ranked_ballots(min_cands=3,
                            max_cands=256,
                            min_voters=1,
                            max_voters=1000):
    n_cands = integers(min_value=min_cands, max_value=max_cands)
    return n_cands.flatmap(lambda n: lists(
        permutations(range(n)), min_size=min_voters, max_size=max_voters))
def invalid_rgb(draw: Callable[[Any], Any]) -> Tuple[int, int, int]:
    v0 = draw(
        st.one_of(st.integers(max_value=-1), st.integers(min_value=0x100)))
    v1 = draw(st.integers(min_value=0, max_value=0xFF))
    v2 = draw(st.integers(min_value=0, max_value=0xFF))
    [r, g, b] = draw(st.permutations([v0, v1, v2]))
    return (r, g, b)
Example #7
0
def mask_strategy(draw):
    dimension = draw(hyp_st.integers(min_value=0, max_value=4))

    mask_strats = []
    shape_strats = []
    default_origin_strats = []

    for i in range(dimension):
        shape_strats = shape_strats + [
            hyp_st.integers(min_value=1, max_value=64)
        ]
        mask_strats = mask_strats + [hyp_st.booleans()]
    shape = draw(hyp_st.tuples(*shape_strats))
    for i in range(dimension):
        default_origin_strats = default_origin_strats + [
            hyp_st.integers(min_value=0, max_value=min(32, shape[i] - 1))
        ]
    default_origin = draw(hyp_st.tuples(*default_origin_strats))
    mask = draw(
        hyp_st.one_of(
            hyp_st.just(None),
            hyp_st.tuples(*mask_strats),
            hyp_st.permutations(([True] * dimension) + (
                [False] * draw(hyp_st.integers(min_value=0, max_value=10)))),
        ))
    return dict(shape=shape, default_origin=default_origin, mask=mask)
Example #8
0
def circuits(draw,
             min_qubits,
             max_qubits,
             min_length,
             max_length,
             allowed_gates=allowed_gates,
             use_all_allowed_gates=False):
    length = draw(integers(min_value=min_length, max_value=max_length))
    num_qubits = draw(integers(min_value=min_qubits, max_value=max_qubits))
    if use_all_allowed_gates:
        circuit_gates = draw(permutations(allowed_gates))
        assert min_length >= len(allowed_gates)
        max_gate_qubits = max((x.nqubit for x in circuit_gates))
        assert min_qubits >= max_gate_qubits
    circuit_gates = draw(
        lists(gates(allowed_gates), min_size=length, max_size=length).filter(
            lambda x: all([y.nqubit <= num_qubits for y in x])))
    result = Circuit()
    for gate in circuit_gates:
        qubits = draw(
            lists(integers(min_value=0, max_value=num_qubits - 1),
                  min_size=gate.nqubit,
                  max_size=gate.nqubit,
                  unique=True))
        result.add_gate(gate, tuple(qubits))
    return result
Example #9
0
def hier_object_data(draw, param_list=None, total_bbox=None):
    """
    Pseudo randomly generate data than models annotations
    of objects.

    DRAW is provided by the hypothesis library and is used
    to choose parameters.

    PARAM_LIST is a list of lists of ObjectStrategyParam namedtuples or a list
    of lists of tuples of ObjectStrategyParam namedtuples.
    The default for PARAM_LIST is HIERARCHY_PARAM.

    TOTAL_BBOX is a bounding box of all objects and defaults to
    (0.0, 0.0, 1.0, 1.0).

    See README.md for more explanation.
    """
    if param_list is None:
        param_list = HIERARCHY_PARAM
    # for consistency, make always param_list be a list of lists of tuples
    param_list = [[
        tuple([j]) if isinstance(j, ObjectStrategyParam) else j for j in i
    ] for i in param_list]
    params = draw(st.one_of([st.just(i) for i in param_list]))
    if total_bbox is None:
        total_bbox = (0.0, 0.0, 1.0, 1.0)
    objects = []
    parents_children = defaultdict(list)
    create_parents_and_children(draw, params, total_bbox, objects,
                                parents_children)
    find_parents_children(objects, parents_children, params)
    find_additional_duplicates(objects, parents_children)
    objects = draw(st.permutations(objects))  # shuffle
    return objects
Example #10
0
def gen_rewrite(draw, hypergraph, signature=DEFAULT_SIGNATURE,
                num_add_nodes=(0, 5), num_add_hyperedges=(0, 20),
                num_remove=(0, 10), num_merge=(0, 10)):
    add_nodes = [Node() for i in range(draw(gen_number(num_add_nodes)))]
    nodes = list(hypergraph.nodes())
    hyperedges = list(hypergraph.hyperedges())

    add_hyperedges = []
    remove = []
    merge = []

    if nodes or add_nodes:
        add_hyperedges = draw(gen_list(gen_hyperedge(add_nodes + nodes,
                                                     signature=signature),
                                       num_add_hyperedges))

    if nodes or hyperedges:
        remove = draw(gen_list(hyperedges, num_remove))

    if nodes:
        merge = draw(gen_list(strategies.tuples(strategies.sampled_from(nodes),
                                                strategies.sampled_from(nodes)),
                              num_merge))

    if draw(strategies.booleans()):
        add_size = len(add_nodes) + len(add_hyperedges)
        add = draw(gen_list(add_nodes + add_hyperedges, add_size))
    else:
        add = draw(strategies.permutations(add_nodes + add_hyperedges))

    return {'remove': remove, 'add': add, 'merge': merge}
Example #11
0
def test_permute(data, t1):
    permutation = data.draw(permutations(range(len(t1.shape))))

    def permute(a):
        return a.permute(*permutation)

    grad_check(permute, t1)
Example #12
0
def complete_graph_fundamental_cycles(draw):
    n = draw(integers(3, 12))
    G = EdgeLabelledGraph(graphs.CompleteGraph(n))
    u = draw(sampled_from(G))
    found = {u}
    tree_edges = set()
    while len(found) < len(G):
        v = draw(sampled_from(G.neighbors(u)))
        if not v in found:
            found.add(v)
            e = G.edge_label(u, v)
            tree_edges.add((u, v, e))
        u = v
    tree_edge_labels = {e for _, _, e in tree_edges}

    def find_cycle(e):
        return [
            label for _, _, label in G.subgraph(
                edges=tree_edges
                | {e}).is_forest(certificate=True, output='edge')[1]
        ]

    cycles = [find_cycle(e) for e in G.edges() if e[2] not in tree_edge_labels]
    cycles = draw(permutations(cycles))
    return G, cycles
Example #13
0
def test_cat(data, x):
    perm = data.draw(permutations(x.dims))
    y = x.transpose(*perm)
    for s in set(x.dims) & set(y.dims):
        c = ntorch.cat([x, y], dim=s)
        c = ntorch.cat([x, c], dim=s)
        c = ntorch.cat([c, x, y], dim=s)
    print(c)
Example #14
0
def sub_lists(sequence: Sequence[Domain],
              *,
              min_size: int = 0,
              max_size: Optional[int] = None) -> SearchStrategy[List[Domain]]:
    if max_size is None:
        max_size = len(sequence)
    return strategies.builds(
        getitem, strategies.permutations(sequence),
        strategies.builds(slice, strategies.integers(min_size, max_size)))
Example #15
0
def enabled_runtime_settings_names(draw):
    shared = draw(shared_config())
    names = configurable_names(shared)
    if names:
        mixed = draw(st.permutations(names))
        cutoff = draw(st.integers(min_value=1, max_value=len(mixed)))
        return mixed[:cutoff]
    else:
        return []
Example #16
0
def test_permute(backend, data):
    "Check permutations for all backends."
    t1 = data.draw(tensors(backend=shared[backend]))
    permutation = data.draw(permutations(range(len(t1.shape))))

    def permute(a):
        return a.permute(*permutation)

    minitorch.grad_check(permute, t1)
Example #17
0
def io_pair_strat_comp(draw):
    n, node_list, output_node_list = draw(sampled_from(NODE_MASTER_LIST))
    output_strat = lists(sampled_from(output_node_list),
                         min_size=3,
                         max_size=10)
    ordering = draw(permutations(node_list))
    possible_edges = list(combinations(ordering, 2))
    edges_strat = lists(sampled_from(possible_edges), min_size=2, unique=True)
    dag_strat = builds(DAG, edge_tuples=edges_strat)
    return draw(tuples(dag_strat, output_strat))
def test_simple_addition_twice(data):
    for congruence in [True, False]:
        h1 = Hypergraph(congruence=congruence)
        h2 = Hypergraph(congruence=congruence)

        to_add1 = data.draw(PE.gen_simple_addition())
        to_add2 = data.draw(PE.gen_simple_addition())

        h1.rewrite(add=to_add1)
        h2.rewrite(add=data.draw(strategies.permutations(to_add1)))

        h1.check_integrity()

        h1.rewrite(add=to_add2)
        h2.rewrite(add=data.draw(strategies.permutations(to_add2)))

        h1.check_integrity()

        assert h1.isomorphic(h2)
Example #19
0
def multiarcs(draw, triangulation=None):
    if triangulation is None: triangulation = draw(triangulations())

    geometric = [0] * triangulation.zeta

    permuted_indices = draw(st.permutations(triangulation.indices))
    num_arcs = draw(st.integers(min_value=1, max_value=len(permuted_indices)))
    for index in permuted_indices[:num_arcs]:
        geometric[index] = draw(st.integers(max_value=-1))

    return triangulation.lamination(geometric)
Example #20
0
def two_strings(draw):
    """Generate two strings. Sometimes they are anagrams of each other"""

    if draw(booleans()):
        # Two random strings.
        return draw(text()), draw(text())
    else:
        # Second string is permutation of first.
        s1 = draw(text())
        s2 = ''.join(draw(permutations(s1)))
        return s1, s2
Example #21
0
    def fill(draw):
        ds = draw(dims(x, max_size=2))
        perm = draw(permutations(range(len(ds))))

        def reorder(ls):
            return [ls[perm[i]] for i in range(len(ls))]

        shape = reorder([x.shape[d] for d in ds])
        np = draw(arrays(dtype, shape, integers(min_value=0, max_value=1)))

        return ntorch.tensor(np, names=reorder(ds)).byte()
Example #22
0
def complete_ranked_ballots(min_cands=3,
                            max_cands=25,
                            min_voters=1,
                            max_voters=100):
    """
    Strategy to generate complete ranked ballot arrays, like those produced by
    elections.impartial_culture()
    """
    n_cands = integers(min_value=min_cands, max_value=max_cands)
    return n_cands.flatmap(lambda n: lists(
        permutations(range(n)), min_size=min_voters, max_size=max_voters))
Example #23
0
def reshapes_of(draw, shape, max_ndims=4):
  """Strategy for valid reshapes of the given shape, rank at most max_ndims."""
  factors = draw(hps.permutations(
      prime_factors(tensorshape_util.num_elements(shape))))
  split_points = sorted(draw(
      hps.lists(hps.integers(min_value=0, max_value=len(factors)),
                min_size=0, max_size=max_ndims - 1)))
  result = ()
  for start, stop in zip([0] + split_points, split_points + [len(factors)]):
    result += (int(np.prod(factors[start:stop])),)
  return result
Example #24
0
class TestParseFilenames:
    def test_parses_prefix_correctly(self):
        filenames = [
            "xxxxOrg_nye_20210128_123742.csv",
            "Org_nye_20210128_123742.csv",
            "garbagebagasdasdads",
        ]

        expected_filename = "Org_nye_20210128_123742.csv"

        actual = los_files.parse_filenames(filenames, "Org_nye", datetime.min)

        actual_filename, _ = one(actual)

        assert expected_filename == actual_filename

    def test_filters_dates_correctly(self):
        filenames = [
            "Org_nye_20200128_123742.csv",
            "Org_nye_20201028_123742.csv",
            "Org_nye_20210128_123742.csv",
        ]

        expected = [
            ("Org_nye_20201028_123742.csv", datetime(2020, 10, 28, 12, 37,
                                                     42)),
            ("Org_nye_20210128_123742.csv", datetime(2021, 1, 28, 12, 37, 42)),
        ]

        actual = los_files.parse_filenames(filenames, "Org_nye",
                                           datetime(2020, 6, 1, 0, 0, 0))

        assert expected == actual

    @given(
        st.permutations([
            "Org_nye_20210101_000000.csv",
            "Org_nye_20200101_000000.csv",
            "Org_nye_20190101_000000.csv",
            "Org_nye_20180101_000000.csv",
        ]))
    def test_sorts_output(self, filenames):
        expected_dates = [
            datetime(2018, 1, 1),
            datetime(2019, 1, 1),
            datetime(2020, 1, 1),
            datetime(2021, 1, 1),
        ]

        actual = los_files.parse_filenames(filenames, "Org_nye", datetime.min)
        actual_dates = list(map(itemgetter(1), actual))

        assert expected_dates == actual_dates
Example #25
0
def choices(seq, size, replace=True):
    """Randomly choose elements from `seq`, producing a tuple of length `size`."""
    if size > len(seq) and not replace:
        raise ValueError("`size` must not exceed the length of `seq` when `replace` is `False`")
    if size > len(seq) and not seq:
        raise ValueError("`size` must be 0, given an empty `seq`")
    inds = list(range(len(seq)))
    if replace:
        strat = st.tuples(*[st.sampled_from(inds)]*size)
    else:
        strat = st.permutations(inds)
    return strat.map(lambda x: tuple(seq[i] for i in x[:size]))
def tensor_data(draw, numbers=floats(), shape=None):
    if shape is None:
        shape = draw(shapes())
    size = int(minitorch.prod(shape))
    data = draw(lists(numbers, min_size=size, max_size=size))
    permute = draw(permutations(range(len(shape))))
    permute_shape = tuple([shape[i] for i in permute])
    reverse_permute = [a[0] for a in sorted(enumerate(permute), key=lambda a: a[1])]
    td = minitorch.TensorData(data, permute_shape)
    ret = td.permute(*reverse_permute)
    assert ret.shape[0] == shape[0]
    return ret
Example #27
0
def election(draw):
    """
    Hypthesis strategy that returns an arbitrarily chosen election.

    First chooses an arbitrary number of candidates between 2 and 10 inclusive.
    Then chooses an arbitrary number of voters greater than 1. Then for each
    voter chooses an arbitrary ranking of the candidates. Returns a list of
    lists of the candidates ranked in order by each voter.

    :rtype: list of list of int
    """
    candidates = list(range(draw(st.integers(2, 10))))
    return draw(st.lists(st.permutations(candidates), min_size=1))
Example #28
0
def _vertices_and_sites(draw: Callable[[st.SearchStrategy[T]], T]
                        ) -> Tuple[List[Point], Set[Requirement]]:
    multipoint: Multipoint = draw(multipoints)
    slice_ = draw(st.integers(min_value=0,
                              max_value=len(multipoint.points) - 1))
    vertices_subset = [multipoint.points[0],
                       *draw(st.permutations(multipoint.points[1:]))[:slice_]]
    requirements_ = draw(st.lists(st.fractions(min_value=MIN_REQUIREMENT),
                                  min_size=slice_ + 1,
                                  max_size=slice_ + 1))
    sites = {Requirement(requirement, point=vertex)
             for vertex, requirement in zip(vertices_subset, requirements_)}
    return multipoint.points, sites
def _bad_tensor_splits(draw):
    lengths = draw(st.lists(st.integers(4, 6), min_size=4, max_size=4))
    batch_size = 4
    element_pairs = [
        (batch, r) for batch in range(batch_size) for r in range(len(lengths))
    ]
    perm = draw(st.permutations(element_pairs))
    ranges = [[(0, 0)] * len(lengths) for _ in range(batch_size)]
    offset = 0

    # Inject some bad samples depending on the batch.
    # Batch 2: length is set to 0. This way, 25% of the samples are empty.
    # Batch 0-1: length is set to half the original length. This way, 50% of the
    # samples are of mismatched length.
    for pair in perm:
        if pair[0] == 2:
            length = 0
        elif pair[0] <= 1:
            length = lengths[pair[1]] // 2
        else:
            length = lengths[pair[1]]
        ranges[pair[0]][pair[1]] = (offset, length)
        offset += length

    data = draw(
        st.lists(
            st.floats(min_value=-1.0, max_value=1.0), min_size=offset, max_size=offset
        )
    )

    key = draw(st.permutations(range(offset)))

    return (
        np.array(data).astype(np.float32),
        np.array(ranges),
        np.array(lengths),
        np.array(key).astype(np.int64),
    )
Example #30
0
 def _to_sizes(size: int, min_element_size: int,
               limit: int) -> Strategy[List[int]]:
     max_sizes = [min_element_size] * size
     indices = cycle(range(size))
     for _ in range(limit - size * min_element_size):
         max_sizes[next(indices)] += 1
     sizes_ranges = [
         range(min_element_size, max_element_size + 1)
         for max_element_size in max_sizes
     ]
     return (strategies.permutations([
         strategies.sampled_from(sizes_range)
         for sizes_range in sizes_ranges
     ]).flatmap(pack(strategies.tuples)).map(list))
def io_pair_strat_trivial_comp(draw):
    n, node_list, output_node_list = draw(sampled_from(NODE_LIST_TRIVIAL))
    output_strat = lists(sampled_from(output_node_list),
                         min_size=MIN_OUTPUT_LEN_TRIVIAL,
                         max_size=MAX_OUTPUT_LEN)
    if n < 2:
        return (DAG([]), draw(output_strat))
    ordering = draw(permutations(node_list))
    possible_edges = list(combinations(ordering, 2))
    edges_strat = lists(sampled_from(possible_edges),
                        min_size=MIN_DAG_EDGES_TRIVIAL,
                        unique=True)
    dag_strat = builds(DAG, edge_tuples=edges_strat)
    return draw(tuples(dag_strat, output_strat))
def closed_object_set(draw):
    ids = {
        'unit': int_keys(draw),
        'organization': uuid_keys(draw),
        'department': uuid_keys(draw),
        'ontologyword': int_keys(draw),
        'ontologytree': int_keys(draw)
    }
    resources = {}
    for key, identifiers in ids.items():
        resources[key] = list(map(make_resource[key](draw, ids), ids[key]))

    resources['ontologyword_details'] = []
    for unit in resources['unit']:
        for oid in draw(permutations(ids['ontologyword'])):
            resources['ontologyword_details'].append(make_ontologyword_details(draw, unit['id'], oid))
    return resources
from __future__ import absolute_import, division, print_function

from hypothesis import given
from hypothesis.errors import InvalidArgument
from hypothesis.strategies import permutations
from tests.common.debug import minimal
from tests.common.utils import fails_with


def test_can_find_non_trivial_permutation():
    x = minimal(permutations(list(range(5))), lambda x: x[0] != 0)

    assert x == [1, 0, 2, 3, 4]


@given(permutations(list(u"abcd")))
def test_permutation_values_are_permutations(perm):
    assert len(perm) == 4
    assert set(perm) == set(u"abcd")


@given(permutations([]))
def test_empty_permutations_are_empty(xs):
    assert xs == []


@fails_with(InvalidArgument)
def test_cannot_permute_non_sequence_types():
    permutations(set()).example()
Example #34
0
def _structure_and_messages(structure):
    messages = ActionStructure.to_eliot(structure, MemoryLogger())
    return st.permutations(messages).map(
        lambda permuted: (structure, permuted))
def test_cannot_permute_non_sequence_types():
    permutations(set()).example()
top_level_deps = [
    ('NoRedInk/top-1', '1.0.0 <= v <= 1.0.0'),
    ('NoRedInk/top-2', '1.0.0 <= v <= 1.0.0'),
    ('NoRedInk/top-3', '1.0.0 <= v <= 1.0.0'),
]

spec_deps = [
    ('NoRedInk/top-1', '1.0.0 <= v <= 1.0.0'),
    ('NoRedInk/top-2', '1.0.0 <= v <= 1.0.0'),
    ('NoRedInk/spec-1', '1.0.0 <= v <= 1.0.0'),
    ('NoRedInk/spec-2', '1.0.0 <= v <= 1.0.0'),
]


@given(top_level_keys=st.permutations(package_skeleton.keys()),
       top_level_deps=st.permutations(top_level_deps),
       spec_keys=st.permutations(package_skeleton.keys()),
       spec_deps=st.permutations(spec_deps))
def test_spec_order_is_preserved(
        tmpdir,
        top_level_keys,
        top_level_deps,
        spec_keys,
        spec_deps):
    top_level_file = tmpdir.join('elm-package.json')
    spec_file = tmpdir.join('spec-elm-package.json')

    top_level = _make_package(top_level_keys, top_level_deps)
    top_level_file.write(json.dumps(top_level))
def test_non_sequence_types_are_deprecated(data, xs):
    p = data.draw(permutations(xs))
    assert xs == set(p)
top_level_deps = [
    ('NoRedInk/top-1', '1.0.0 <= v <= 1.0.0'),
    ('NoRedInk/top-2', '1.0.0 <= v <= 1.0.0'),
    ('NoRedInk/top-3', '1.0.0 <= v <= 1.0.0'),
]

spec_deps = [
    ('NoRedInk/top-1', '1.0.0 <= v <= 1.0.0'),
    ('NoRedInk/top-2', '1.0.0 <= v <= 1.0.0'),
    ('NoRedInk/spec-1', '1.0.0 <= v <= 1.0.0'),
    ('NoRedInk/spec-2', '1.0.0 <= v <= 1.0.0'),
]


@given(top_level_deps=st.permutations(top_level_deps),
       spec_deps=st.permutations(spec_deps))
def test_spec_order_is_preserved(
        tmpdir,
        top_level_deps,
        spec_deps):
    top_level_file = tmpdir.join('elm-native-package.json')
    spec_file = tmpdir.join('spec-elm-native-package.json')

    top_level = OrderedDict(top_level_deps)
    top_level_file.write(json.dumps(top_level))

    spec = OrderedDict(spec_deps)
    spec_file.write(json.dumps(spec))

    native_deps_sync.sync_versions(
    def make_unit(uid):
        # Required fields
        result = {
            'id': uid,
            'accessibility_viewpoints': accessibility_viewpoints(draw),
            'dept_id': str(draw(sampled_from(resource_ids['department']))),
            'org_id': str(draw(sampled_from(resource_ids['organization']))),
            'ontologytree_ids': draw(permutations(resource_ids['ontologytree'])),
            'provider_type': draw(sampled_from(PROVIDER_TYPES)),
            'organizer_type': draw(sampled_from(ORGANIZER_TYPES)),
            'manual_coordinates': draw(booleans()),
            # TODO: cannot test is_public=False until there is a mechanism
            # for getting non-public units from the API.
            'is_public': True,
            # TODO: map to another field
        }
        result.update(translated_field(draw, 'name', allow_missing=False))

        def add_optional_field(name, strategy):
            val = draw(one_of(none(), strategy))
            if val is not None:
                event('unit.{}: optional field given value'.format(name))
                result[name] = val
            else:
                event('unit.{}: optional field missing'.format(name))

        def add_optional_text_field(name):
            add_optional_field(name, text(max_size=50))

        add_optional_field('address_city', sampled_from(MUNICIPALITIES))
        add_optional_field('address_zip', text(max_size=10))
        add_optional_field('organizer_business_id', text(max_size=10))
        add_optional_field('organizer_name', text(max_size=10))

        for field in ['accessibility_email',
                      'accessibility_www',
                      'email',
                      'fax',
                      'phone',
                      'picture_entrance_url',
                      'picture_url',
                      'streetview_entrance_url']:
            add_optional_text_field(field)
        add_optional_field('data_source_url', text(max_size=30))

        result.update(translated_field(draw, 'address_postal_full', allow_missing=True))
        result.update(translated_field(draw, 'call_charge_info', allow_missing=True))
        result.update(translated_field(draw, 'desc', allow_missing=True))
        result.update(translated_field(draw, 'picture_caption', allow_missing=True))

        # Extra searchwords

        add_extra_searchwords(draw, result)

        add_optional_field('sources',
                           lists(make_source(), min_size=1, max_size=2))

        has_coordinates = draw(booleans())
        if has_coordinates:
            result['longitude'] = draw(floats(min_value=24, max_value=26))
            result['latitude'] = draw(floats(min_value=58, max_value=62))

        return result
def election(draw, max_candidates=10):
    candidates = list(range(draw(st.integers(2, max_candidates))))
    return draw(
        st.lists(st.permutations(candidates), min_size=1)
    )
def test_can_find_non_trivial_permutation():
    x = find(
        permutations(list(range(5))), lambda x: x[0] != 0
    )

    assert x == [1, 0, 2, 3, 4]
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
#
# END HEADER

from __future__ import division, print_function, absolute_import

from hypothesis import find, given
from hypothesis.strategies import permutations


def test_can_find_non_trivial_permutation():
    x = find(
        permutations(list(range(5))), lambda x: x[0] != 0
    )

    assert x == [1, 0, 2, 3, 4]


@given(permutations(list(u'abcd')))
def test_permutation_values_are_permutations(perm):
    assert len(perm) == 4
    assert set(perm) == set(u'abcd')


@given(permutations([]))
def test_empty_permutations_are_empty(xs):
    assert xs == []