Passed
Push — master ( f41365...23c626 )
by Amresh
01:22
created

schema_to_object_builder()   B

Complexity

Conditions 6

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 14
rs 8.6666
c 0
b 0
f 0
cc 6
nop 2
1
import random
2
from fastest.fuzzers.primitive_fuzzer.fuzz import random_integers, random_ascii_chars, random_float
3
4
5
def build_one_of_type(item_type, p=1.0):
6
    empty_values_for_types = {
7
        "str": random_ascii_chars,
8
        "int": random_integers,
9
        "float": random_float,
10
        "list": lambda: [],
11
        "dict": lambda: {},
12
        "null": lambda: None
13
    }
14
    basic_types = ['str', 'int', 'float', 'list', 'dict', 'null']
15
    mutation = random.random()
16
    return empty_values_for_types[item_type] \
17
        if p > mutation \
18
        else empty_values_for_types[random.choice(basic_types)]
19
20
21
def schema_to_object_builder(schema, p=1.0):
22
    mutation = random.random()
23
    root_object = build_one_of_type(schema['type'])()
24
25
    if isinstance(root_object, list):
26
        if p > mutation:
27
            root_object.append(schema_to_object_builder(schema['inner'], p=p))
28
29
    elif isinstance(root_object, dict):
30
        for prop in schema['inner']:
31
            if p > mutation:
32
                root_object[prop['name']] = schema_to_object_builder(prop, p=p)
33
34
    return root_object
35