File: random_gen.py

package info (click to toggle)
python-model-bakery 1.20.5-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 532 kB
  • sloc: python: 4,298; sh: 149; makefile: 21
file content (378 lines) | stat: -rw-r--r-- 10,084 bytes parent folder | download | duplicates (2)
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
45
46
47
48
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
112
113
114
115
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
"""Generators are callables that return a value used to populate a field.

If this callable has a `required` attribute (a list, mostly), for each
item in the list, if the item is a string, the field attribute with the
same name will be fetched from the field and used as argument for the
generator. If it is a callable (which will receive `field` as first
argument), it should return a list in the format (key, value) where key
is the argument name for generator and value is the value for that
argument.
"""

import string
import warnings
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from os.path import abspath, dirname, join
from random import Random
from typing import Any, Callable, List, Optional, Tuple, Union
from uuid import UUID

from django.core.files.base import ContentFile
from django.db.models import Field, Model
from django.utils.timezone import now

MAX_LENGTH = 300
# Using sys.maxint here breaks a bunch of tests when running against a
# Postgres database.
MAX_INT = 100000000000

baker_random = Random()  # noqa: S311


def get_content_file(content: bytes, name: str) -> ContentFile:
    return ContentFile(content, name=name)


def gen_file_field() -> ContentFile:
    name = "mock_file.txt"
    file_path = abspath(join(dirname(__file__), name))
    with open(file_path, "rb") as f:
        return get_content_file(f.read(), name=name)


def gen_image_field() -> ContentFile:
    name = "mock_img.jpeg"
    file_path = abspath(join(dirname(__file__), name))
    with open(file_path, "rb") as f:
        return get_content_file(f.read(), name=name)


def gen_from_list(a_list: Union[List[str], range]) -> Callable:
    """Make sure all values of the field are generated from a list.

    Examples:
        Here how to use it.

        >>> from baker import Baker
        >>> class ExperienceBaker(Baker):
        >>>     attr_mapping = {'some_field': gen_from_list(['A', 'B', 'C'])}

    """
    return lambda: baker_random.choice(list(a_list))


# -- DEFAULT GENERATORS --


def gen_from_choices(choices: List) -> Callable:
    choice_list = []
    for value, label in choices:
        if isinstance(label, (list, tuple)):
            for val, _lbl in label:
                choice_list.append(val)
        else:
            choice_list.append(value)
    return gen_from_list(choice_list)


def gen_integer(min_int: int = -MAX_INT, max_int: int = MAX_INT) -> int:
    return baker_random.randint(min_int, max_int)


def gen_float() -> float:
    return baker_random.random() * gen_integer()


def gen_decimal(max_digits: int, decimal_places: int) -> Decimal:
    def num_as_str(x: int) -> str:
        return "".join([str(baker_random.randint(0, 9)) for _ in range(x)])

    if decimal_places:
        return Decimal(
            f"{num_as_str(max_digits - decimal_places - 1)}.{num_as_str(decimal_places)}"
        )

    return Decimal(num_as_str(max_digits))


gen_decimal.required = ["max_digits", "decimal_places"]  # type: ignore[attr-defined]


def gen_date() -> date:
    return now().date()


def gen_datetime() -> datetime:
    return now()


def gen_time() -> time:
    return now().time()


def gen_string(max_length: int) -> str:
    return "".join(baker_random.choice(string.ascii_letters) for _ in range(max_length))


def _gen_string_get_max_length(field: Field) -> Tuple[str, int]:
    max_length = getattr(field, "max_length", None)
    if max_length is None:
        max_length = MAX_LENGTH
    return "max_length", max_length


gen_string.required = [_gen_string_get_max_length]  # type: ignore[attr-defined]


def gen_slug(max_length: int) -> str:
    valid_chars = string.ascii_letters + string.digits + "_-"
    return "".join(baker_random.choice(valid_chars) for _ in range(max_length))


gen_slug.required = ["max_length"]  # type: ignore[attr-defined]


def gen_text() -> str:
    warnings.warn(
        "\n"
        "Accessing `model_bakery.random_gen.gen_text` is deprecated "
        "and will be removed in a future major release. Please use "
        "`model_bakery.random_gen.gen_string` instead."
        "\n",
        DeprecationWarning,
        stacklevel=2,
    )
    return gen_string(MAX_LENGTH)


def gen_boolean() -> bool:
    return baker_random.choice((True, False))


def gen_null_boolean():
    return baker_random.choice((True, False, None))


def gen_url() -> str:
    return f"http://www.{gen_string(30)}.com/"


def gen_email() -> str:
    return f"{gen_string(10)}@example.com"


def gen_ipv6() -> str:
    return ":".join(format(baker_random.randint(1, 65535), "x") for _ in range(8))


def gen_ipv4() -> str:
    return ".".join(str(baker_random.randint(1, 255)) for _ in range(4))


def gen_ipv46() -> str:
    ip_gen = baker_random.choice([gen_ipv4, gen_ipv6])
    return ip_gen()


def gen_ip(protocol: str, default_validators: List[Callable]) -> str:
    from django.core.exceptions import ValidationError

    protocol = (protocol or "").lower()

    if not protocol:
        field_validator = default_validators[0]
        dummy_ipv4 = "1.1.1.1"
        dummy_ipv6 = "FE80::0202:B3FF:FE1E:8329"
        try:
            field_validator(dummy_ipv4)
            field_validator(dummy_ipv6)
            generator = gen_ipv46
        except ValidationError:
            try:
                field_validator(dummy_ipv4)
                generator = gen_ipv4
            except ValidationError:
                generator = gen_ipv6
    elif protocol == "ipv4":
        generator = gen_ipv4
    elif protocol == "ipv6":
        generator = gen_ipv6
    else:
        generator = gen_ipv46

    return generator()


gen_ip.required = ["protocol", "default_validators"]  # type: ignore[attr-defined]


def gen_byte_string(max_length: int = 16) -> bytes:
    generator = (baker_random.randint(0, 255) for x in range(max_length))
    return bytes(generator)


def gen_interval(interval_key: str = "milliseconds", offset: int = 0) -> timedelta:
    interval = gen_integer() + offset
    kwargs = {interval_key: interval}
    return timedelta(**kwargs)


def gen_content_type():
    from django.apps import apps
    from django.contrib.contenttypes.models import ContentType

    try:
        return ContentType.objects.get_for_model(baker_random.choice(apps.get_models()))
    except (AssertionError, RuntimeError):
        # AssertionError is raised by Django's test framework when db access is not available:
        # https://github.com/django/django/blob/stable/4.0.x/django/test/testcases.py#L150
        # RuntimeError is raised by pytest-django when db access is not available:
        # https://github.com/pytest-dev/pytest-django/blob/v4.5.2/pytest_django/plugin.py#L709
        warnings.warn(
            "Database access disabled, returning ContentType raw instance", stacklevel=1
        )
        return ContentType()


def gen_uuid() -> UUID:
    import uuid

    return uuid.uuid4()


def gen_array():
    return []


def gen_json():
    return {}


def gen_hstore():
    return {}


def _fk_model(field: Field) -> Tuple[str, Optional[Model]]:
    try:
        return ("model", field.related_model)
    except AttributeError:
        return ("model", field.related.parent_model)


def _prepare_related(
    model: str, _create_files=False, **attrs: Any
) -> Union[Model, List[Model]]:
    from .baker import prepare

    return prepare(model, **attrs)


def gen_related(model, _create_files=False, **attrs):
    from .baker import make

    return make(model, _create_files=_create_files, **attrs)


gen_related.required = [_fk_model, "_using"]  # type: ignore[attr-defined]
gen_related.prepare = _prepare_related  # type: ignore[attr-defined]


def gen_m2m(model, _create_files=False, **attrs):
    from .baker import MAX_MANY_QUANTITY, make

    return make(
        model, _create_files=_create_files, _quantity=MAX_MANY_QUANTITY, **attrs
    )


gen_m2m.required = [_fk_model, "_using"]  # type: ignore[attr-defined]


# GIS generators


def gen_coord() -> float:
    return baker_random.uniform(0, 1)


def gen_coords() -> str:
    return f"{gen_coord()} {gen_coord()}"


def gen_point() -> str:
    return f"POINT ({gen_coords()})"


def _gen_line_string_without_prefix() -> str:
    return f"({gen_coords()}, {gen_coords()})"


def gen_line_string() -> str:
    return f"LINESTRING {_gen_line_string_without_prefix()}"


def _gen_polygon_without_prefix() -> str:
    start = gen_coords()
    return f"(({start}, {gen_coords()}, {gen_coords()}, {start}))"


def gen_polygon() -> str:
    return f"POLYGON {_gen_polygon_without_prefix()}"


def gen_multi_point() -> str:
    return f"MULTIPOINT (({gen_coords()}))"


def gen_multi_line_string() -> str:
    return f"MULTILINESTRING ({_gen_line_string_without_prefix()})"


def gen_multi_polygon() -> str:
    return f"MULTIPOLYGON ({_gen_polygon_without_prefix()})"


def gen_geometry():
    return gen_point()


def gen_geometry_collection() -> str:
    return f"GEOMETRYCOLLECTION ({gen_point()})"


def gen_pg_numbers_range(number_cast: Callable[[int], Any]) -> Callable:
    def gen_range():
        try:
            from psycopg.types.range import Range
        except ImportError:
            from psycopg2._range import NumericRange as Range

        base_num = gen_integer(1, 100000)
        return Range(number_cast(-1 * base_num), number_cast(base_num))

    return gen_range


def gen_date_range():
    try:
        from psycopg.types.range import DateRange
    except ImportError:
        from psycopg2.extras import DateRange

    base_date = gen_date()
    interval = gen_interval(offset=24 * 60 * 60 * 1000)  # force at least 1 day interval
    args = sorted([base_date - interval, base_date + interval])
    return DateRange(*args)


def gen_datetime_range():
    try:
        from psycopg.types.range import TimestamptzRange
    except ImportError:
        from psycopg2.extras import DateTimeTZRange as TimestamptzRange

    base_datetime = gen_datetime()
    interval = gen_interval()
    args = sorted([base_datetime - interval, base_datetime + interval])
    return TimestamptzRange(*args)