from typing import OrderedDict


def sort_constraint_dict(d):
    """
    Helper function for tests, to sort a constraints dictionary (read
    from a .tdda file) into alphabetical order by field name, and with
    all of the individual constraints in the same order in which they
    are generated.
    """
    constraintkey = ['type', 'min', 'max', 'min_length', 'max_length',
                     'sign', 'max_nulls', 'no_duplicates', 'allowed_values',
                     'rex']
    fields = OrderedDict((
        (f, OrderedDict(((k, kv)
                         for k, kv in sorted(v.items(),
                                             key=lambda x:
                                                  constraintkey.index(x[0])))))
        for f, v in sorted(d['fields'].items())
    ))
    return OrderedDict((('fields', fields),))