ValueGenerator.py 7.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python2
# -*- coding: utf-8 -*-

# pylint: disable=C0302
"""
    ASN.1 Value Editor - ASN.1 Value Generator

    Two functions are provided:

    compute_random_value - Generate a random GSER string for a given ASN.1 type
    compute_combinations - Yields all combinations of values of an ASN.1 type

    Copyright (c) 2016 European Space Agency

    Author: Maxime Perrotin / contact maxime.perrotin@esa.int
"""

__all__ = ['compute_random_value', 'compute_combinations']

import random
import itertools
import opengeode


# Set of functions used by the simulator to compute a random value for
# a given ASN.1 type, return a Value Notation string
def compute_random_value(asn1_ty, pool):
    ''' Top-level, type-dispatching function
    pool is the set of types from process.dataview attribute '''
    basic = opengeode.ogParser.find_basic_type(asn1_ty.type, pool)
    if basic.kind.startswith('Integer'):
        return rand_int(basic)
    elif basic.kind == 'BooleanType':
        return rand_bool(basic)
    elif basic.kind.startswith('Real'):
        return rand_real(basic)
    elif basic.kind == 'EnumeratedType':
        return rand_enum(basic)
    elif basic.kind == 'ChoiceType':
        return compute_random_choice(basic, pool)
    elif basic.kind in ('SequenceType', 'SetType'):
        return compute_random_sequence(basic, pool)
    elif basic.kind in ('SequenceOfType', 'SetOfType'):
        return compute_random_sequenceof(basic, pool)
Maxime Perrotin's avatar
Maxime Perrotin committed
45
46
47
48
    elif basic.kind.endswith('StringType'):
        return '"' + 'X' * random.randint(int(basic.Min), int(basic.Max)) + '"'
    else:
        raise NotImplementedError('Type not randomizable yet:' + basic.kind)
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


# Random values for basic types
rand_int = lambda ty: str(random.randint(long(ty.Min), long(ty.Max)))
rand_real = lambda ty: str(random.uniform(float(ty.Min), float(ty.Max)))
rand_bool = lambda _: random.choice(['TRUE', 'FALSE'])
rand_enum = lambda ty: random.choice(ty.EnumValues.keys())


def compute_random_choice(asn1_ty, pool):
    ''' Select randomly a choice item and set a random value '''
    choice = random.choice(asn1_ty.Children.keys())
    value_ty = asn1_ty.Children[choice]
    value = compute_random_value(value_ty, pool)
    return '{}: {}'.format(choice, value)


def compute_random_sequence(asn1_ty, pool):
    ''' Compute randomly the values of SEQUENCE fields '''
    res = []
    for name, ty in asn1_ty.Children.viewitems():
        res.append('{} {}'.format(name, compute_random_value(ty, pool)))
    return '{{ {} }}'.format(', '.join(res))


def compute_random_sequenceof(asn1_ty, pool):
    ''' Compute a list of a random size and random values '''
    size = random.randint(int(asn1_ty.Min), int(asn1_ty.Max))
    elems = []
    for _ in xrange(size):
        elems.append(compute_random_value(asn1_ty, pool))
    return  '{{ {} }}'.format(', '.join(elems))


# Set of functions used by the simulator to compute the combination input
# parameters for each ASN.1 data type. Yield ASN.1 Value Notation strings
# ASN.1 types must be in the format generated by ASN1SCC Python backend
def compute_combinations(asn1_ty, pool):
    ''' Top-level, type-dispatching function
    "pool" is the set of types, found in the process.dataview attribute '''
    basic = opengeode.ogParser.find_basic_type(asn1_ty.type, pool)
    # Python2 has no "yield from"...
    if basic.kind.startswith('Integer'):
        for each in compute_integer_combinations(basic):
            yield each
    elif basic.kind == 'BooleanType':
        for each in compute_boolean_combinations(basic):
            yield each
    elif basic.kind.startswith('Real'):
        for each in compute_real_combinations(basic):
            yield each
    elif basic.kind == 'EnumeratedType':
        for each in compute_enumerated_combinations(basic):
            yield each
    elif basic.kind == 'ChoiceType':
        for each in compute_choice_combinations(basic, pool):
            yield each
    elif basic.kind in ('SequenceType', 'SetType'):
        for each in compute_sequence_combinations(basic, pool):
            yield each
    elif basic.kind in ('SequenceOfType', 'SetOfType'):
        for each in compute_sequenceof_combinations(basic, pool):
            yield each
Maxime Perrotin's avatar
Maxime Perrotin committed
112
113
114
    elif basic.kind.endswith('StringType'):
        # Strings
        for n in xrange(int(basic.Min), int(basic.Max) + 1):
115
            yield '"' + 'X' * n + '"'
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154


def compute_integer_combinations(asn1_ty, max_iter=0):
    ''' Generator returning all integer values, with optional limit '''
    # Do not use xrange, it needs a value that fits in a C long
    max_iter = (long(asn1_ty.Min)
                + max_iter) if max_iter != 0 else long(asn1_ty.Max)
    for each in itertools.count(long(asn1_ty.Min)):
        if each > max_iter:
            break
        yield str(each)


def compute_real_combinations(asn1_ty):
    ''' Generator returning three real values only (set is infinite) '''
    yield asn1_ty.Min
    yield str((float(asn1_ty.Max) + float(asn1_ty.Min)) / 2.0)
    yield asn1_ty.Max


def compute_boolean_combinations(asn1_ty):
    ''' Generator returning all combinations of boolean '''
    yield 'TRUE'
    yield 'FALSE'


def compute_enumerated_combinations(asn1_ty):
    ''' Generator returning all combinations of enumerated '''
    for each in asn1_ty.EnumValues.viewkeys():
        yield each


def compute_choice_combinations(asn1_ty, pool):
    ''' Generator returning all combinations of choice components '''
    for discr, value_ty in asn1_ty.Children.viewitems():
        for each in compute_combinations(value_ty, pool):
            yield '{}: {}'.format(discr, each)


155
156
157
158
159
160
161
162
163
164
165
def myproduct(*iterables):
    ''' Custom implementation of itertools.product - standard product
    has to consume the iterables completely before making the product,
    meaning it is useless with large iterable due to memory usage '''
    if len(iterables) == 0:
        raise StopIteration
    else:
        for item in iterables[0]():
            for items in myproduct(*iterables[1:]):
                yield (item, ) + items

166
167
168
def compute_sequence_combinations(asn1_ty, pool):
    ''' Generator returning all combinations of SEQUENCE types '''
    # Prepare generators to compute combinations of each field
169
170
    elems = [lambda: compute_combinations(sort, pool)
             for sort in asn1_ty.Children.viewvalues()]
171
    # Combine all field generators to get the complete set of values
172
173
174
175
176
177
    elems_lambda = [lambda: elem() for elem in elems]
    # This is not quite right. XXX

    #for each in itertools.product(*elems):
    for each in myproduct(*elems_lambda):
        # "each" contains a generator per field in the SEQUENCE
178
179
180
        # each is a tuple with values for the sequence, join with fieldnames
        pairs = itertools.izip(asn1_ty.Children.viewkeys(), each)
        res = ('{} {}'.format(name, value) for name, value in pairs)
181
182
        res_yield = '{{ {} }}'.format(', '.join(res))
        yield res_yield
183
184
185
186
187
188
189
190
191


def compute_sequenceof_combinations(asn1_ty, pool):
    ''' Generator returning all combinations of arrays '''
    for size in xrange(int(asn1_ty.Min), int(asn1_ty.Max) + 1):
        elems = []
        for _ in xrange(size):
            elems.append(compute_combinations(asn1_ty, pool))
        for each in itertools.product(*elems):
192
193
            res = '{{ {} }}'.format(', '.join(each))
            yield res