This file is indexed.

/usr/lib/python2.7/dist-packages/model_mommy/random_gen.py is in python-model-mommy 1.5.1-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
# -*- coding:utf-8 -*-
"""
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 decimal import Decimal
from os.path import abspath, join, dirname
from random import randint, choice, random, uniform

import six
from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile

from model_mommy.timezone import now

# Map unicode to str in Python 2.x since bytes can be used
try:
    str = unicode
except NameError:
    pass

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


def get_content_file(content, name):
    return ContentFile(content, name=name)


def gen_file_field():
    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():
    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(L):
    '''Makes sure all values of the field are generated from the list L
    Usage:
    from mommy import Mommy
    class KidMommy(Mommy):
      attr_mapping = {'some_field':gen_from_list([A, B, C])}
    '''
    return lambda: choice(list(L))


# -- DEFAULT GENERATORS --


def gen_from_choices(C):
    choice_list = []
    for value, label in C:
        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=-MAX_INT, max_int=MAX_INT):
    return randint(min_int, max_int)


def gen_float():
    return random() * gen_integer()


def gen_decimal(max_digits, decimal_places):
    num_as_str = lambda x: ''.join([str(randint(0, 9)) for i in range(x)])
    if decimal_places:
        return Decimal("%s.%s" % (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']


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


def gen_datetime():
    return now()


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


def gen_string(max_length):
    return str(''.join(choice(string.ascii_letters) for i in range(max_length)))


gen_string.required = ['max_length']


def gen_slug(max_length):
    valid_chars = string.ascii_letters + string.digits + '_-'
    return str(''.join(choice(valid_chars) for i in range(max_length)))


gen_slug.required = ['max_length']


def gen_text():
    return gen_string(MAX_LENGTH)


def gen_boolean():
    return choice((True, False))


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


def gen_url():
    return str('http://www.%s.com/' % gen_string(30))


def gen_email():
    return "%s@example.com" % gen_string(10)


def gen_ipv6():
    return ":".join(format(randint(1, 65535), 'x') for i in range(8))


def gen_ipv4():
    return ".".join(str(randint(1, 255)) for i in range(4))


def gen_ipv46():
    ip_gen = choice([gen_ipv4, gen_ipv6])
    return ip_gen()


def gen_ip(protocol, default_validators):
    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']


def gen_byte_string(max_length=16):
    generator = (randint(0, 255) for x in range(max_length))
    if six.PY2:
        return "".join(map(chr, generator))
    elif six.PY3:
        return bytes(generator)


def gen_interval(interval_key='milliseconds'):
    from datetime import timedelta
    interval = gen_integer()
    kwargs = {interval_key: interval}
    return timedelta(**kwargs)


def gen_content_type():
    from django.contrib.contenttypes.models import ContentType
    try:
        # for >= 1.7
        from django.apps import apps
        get_models = apps.get_models
    except ImportError:
        # Deprecated
        from django.db.models import get_models
    try:
        return ContentType.objects.get_for_model(choice(get_models()))
    except AssertionError:
        warnings.warn('Database access disabled, returning ContentType raw instance')
        return ContentType()


def gen_uuid():
    import uuid
    return uuid.uuid4()


def gen_array():
    return []


def gen_json():
    return {}


def gen_hstore():
    return {}


def _fk_model(field):
    try:
        return ('model', field.related_model)
    except AttributeError:
        return ('model', field.related.parent_model)


def _prepare_related(model, **attrs):
    from .mommy import prepare
    return prepare(model, **attrs)


def gen_related(model, **attrs):
    from .mommy import make
    return make(model, **attrs)


gen_related.required = [_fk_model]
gen_related.prepare = _prepare_related


def gen_m2m(model, **attrs):
    from .mommy import make, MAX_MANY_QUANTITY
    return make(model, _quantity=MAX_MANY_QUANTITY, **attrs)


gen_m2m.required = [_fk_model]


# GIS generators

def gen_coord():
    return uniform(0, 1)


def gen_coords():
    return '{x} {y}'.format(x=gen_coord(), y=gen_coord())


def gen_point():
    return 'POINT ({})'.format(
        gen_coords(),
    )


def _gen_line_string_without_prefix():
    return '({}, {})'.format(
        gen_coords(),
        gen_coords(),
    )


def gen_line_string():
    return 'LINESTRING {}'.format(
        _gen_line_string_without_prefix()
    )


def _gen_polygon_without_prefix():
    start = gen_coords()
    return '(({}, {}, {}, {}))'.format(
        start,
        gen_coords(),
        gen_coords(),
        start
    )


def gen_polygon():
    return 'POLYGON {}'.format(
        _gen_polygon_without_prefix(),
    )


def gen_multi_point():
    return 'MULTIPOINT (({}))'.format(
        gen_coords(),
    )


def gen_multi_line_string():
    return 'MULTILINESTRING ({})'.format(
        _gen_line_string_without_prefix(),
    )


def gen_multi_polygon():
    return 'MULTIPOLYGON ({})'.format(
        _gen_polygon_without_prefix(),
    )


def gen_geometry():
    return gen_point()


def gen_geometry_collection():
    return 'GEOMETRYCOLLECTION ({})'.format(
        gen_point(),
    )