Ejemplo n.º 1
0
    def test_canonical_published(self):

        headline = words(random.randint(5,10), common=False)
        a1, created = Article.objects.get_or_create( headline=headline,
            slug=slugify(headline),
            summary=sentence(),
            author=words(1,common=False),
            body=paragraphs(5),
            publish=True)

        a2, created = Article.objects.get_or_create( headline=headline,
            slug=slugify(headline),
            summary=sentence(),
            author=words(1,common=False),
            body=paragraphs(5),
            publish=True)

        self.assertEqual(2, len(Article.objects.get_published()))

        # set a2 to be a translation of a1
        a2.translation_of = a1
        a2.save()

        # we only expect 1 canonical object now as a2 is a translation of a1
        self.assertEqual(1, len(Article.objects.get_published()))
Ejemplo n.º 2
0
    def setUp(self):
        self.myuser = User.objects.create_user('jsmith',
                                               '*****@*****.**',
                                               'secret')

        self.section1 = Section.objects.create(title='Section1')
        self.section2 = Section.objects.create(title='Section2')
        self.article1 = Article.objects.create(
            title='This is Article 1',
            author=self.myuser,
            summary_html=words(7),
            content_html=paragraphs(2),
            section=self.section1
        )

        self.article1 = Article.objects.create(
            title='This is Article 2',
            author=self.myuser,
            summary_html=words(5),
            content_html=paragraphs(3),
            section=self.section1
        )

        self.article3 = Article.objects.create(
            title='This is Published',
            author=self.myuser,
            summary_html=words(5),
            content_html=paragraphs(3),
            section=self.section1,
            published=now()
        )
Ejemplo n.º 3
0
    def email(self):
        """Random mail address."""
        username = lorem_ipsum.words(1, common=False)
        domain = lorem_ipsum.words(1, common=False)
        termination = random.choice([u'.com', u'.org', u'.net'])

        return "{0}@{1}{2}".format(username, domain, termination)
Ejemplo n.º 4
0
	def generate_CharField(self,**kwargs):
		"""
		Generates char data for any CharField.
		Supported field extras:
		field_extras={
			'myfield':{
				'spaces':False|True, #(Default: True) #whether or not to allow spaces
				'word_count':3, #if specified, only 3 words will be generatd, if not specified, random between 1 and 4.
				'word_range:(2,5), #if specified, overrides the 'word_count' option, and will generate 2-5 random words.
			}
		}
		"""
		salt=""
		field_extras=kwargs.get("field_extras",False)
		field = kwargs.get("field", ())
		if field.choices:return random.choice(field.choices)[0]
		if kwargs.get('unique',False): salt="".join([random.choice(string.digits) for i in range(random.randint(1,16))])
		word_count=self._get_field_option(field_extras,'word_count',-1)
		word_range=self._get_field_option(field_extras,'word_range',-1)
		if isinstance(word_range,tuple) and len(word_range)>1:
			result="%s %s" % (words(random.randint(word_range[0],word_range[1]),common=False),salt)
		elif word_count > 0:
			result="%s %s" % (words(word_count,common=False),salt)
		else:
			result="%s %s" % (words(random.randint(1,4),common=False),salt)
		max_length=kwargs.get('max_length',None)
		length=len(result)
		if max_length and length > max_length: result=result[length-max_length:] #chop off too many chars for max length
		if not self._get_field_option(field_extras,"spaces",True) and word_count == -1 and word_range == -1:
			result=result.replace(" ","")
		result=re.sub(r' $','',result)
		return result
Ejemplo n.º 5
0
    def generate_EmailField(self, **kwargs):
        """
		Generates a random lipsum email address.
		"""
        front = words(1, common=False)
        back = words(1, common=False)
        #side to side
        email = front + "@" + back + ".com"
        return email
Ejemplo n.º 6
0
	def generate_EmailField(self,**kwargs):
		"""
		Generates a random lipsum email address.
		"""
		front=words(1,common=False)
		back=words(1,common=False)
		#side to side
		email=front+"@"+back+".com"
		return email
Ejemplo n.º 7
0
def generate():
    for i in xrange(random.randint(1, 10)):
        announcement = Announcement.objects.create(
            title=capfirst(words(8, common=False)),
            content=words(random.randint(1, 1000), common=False),
            creator=User.objects.order_by('?')[0],
            site_wide=random.random() > 0.5,
            members_only=random.random() > 0.5)
        print "Created Announcement: %s" % (announcement, )
Ejemplo n.º 8
0
def generate():
    for i in xrange(random.randint(1, 10)):
        announcement = Announcement.objects.create(
            title=capfirst(words(8, common=False)),
            content=words(random.randint(1, 1000), common=False),
            creator=User.objects.order_by('?')[0],
            site_wide=random.random() > 0.5,
            members_only=random.random() > 0.5
        )
        print "Created Announcement: %s" % (announcement,)
Ejemplo n.º 9
0
def setup_test_job_posts(test_jobs_pattern):
    """
    Sets up a certain number of test job posts.

    This method requires that at least one models.Position is already
    set up.

    Attributes:
      test_jobs_pattern: (iterable of dicts)
        This attribute should follow the pattern of:
          [{'approved': True, 'expired': False},
           {'approved': False, 'expired': True},
           {'approved': False, 'expired': False},
           {'approved': True, 'expired': True}]

        ... where each dictionary describes the fake job post
        being set up.  'approved' specifies whether or not the
        posting has been approved, and 'expired' describes whether
        or not the expiration date has been passed or not.

        Note that the remainder of the attributes will be filled with
        random lorem ipsum text, with the exception of Position, which
        will be any randomly selected position, and when_posted, which
        will always be datetime.datetime.now()

    Returns:
      The ids of the fake job posts.
    """
    fake_job_ids = []
    for pattern in test_jobs_pattern:
        init_dict = {
            'posters_name': lorem_ipsum.words(3, common=False),
            'work_hours': lorem_ipsum.words(5, common=False),
            'description': '\n'.join(lorem_ipsum.paragraphs(4, common=False)),
            'position': random.choice(models.Position.objects.all()),
            'email': '%s@%s.%s' % tuple(
                lorem_ipsum.words(3, common=False).split()),
            'contact_information': '\n'.join(
                lorem_ipsum.paragraphs(4, common=False)),
            'when_posted': datetime.datetime.now()}

        init_dict['approved'] = pattern['approved']

        expiration_delta = datetime.timedelta(days=settings.JOBBOARD_POSTS_EXPIRE_DAYS)
        if pattern['expired']:
            init_dict['expiration_date'] = \
                datetime.date.today() - expiration_delta
        else:
            init_dict['expiration_date'] = \
                datetime.date.today() + expiration_delta

        new_jobpost = models.JobPost.objects.create(**init_dict)
        fake_job_ids.append(new_jobpost.id)

    return fake_job_ids
Ejemplo n.º 10
0
	def make_example_object(self, model = None, pk = 1):
		from django.contrib.webdesign import lorem_ipsum
		from django.template.defaultfilters import slugify
		from datetime import datetime
		import random
		
		model = model or self.model
		opts = model._meta
		fields = (field for field in opts.local_fields + opts.local_many_to_many)
		kwargs = {
			'id': pk
		}
		
		for field in fields:
			if hasattr(field, 'default') and field.default != models.fields.NOT_PROVIDED:
				if isinstance(field, models.ForeignKey):
					value = field.rel.to.objects.get(pk = field.default)
				else:
					value = field.default
			elif hasattr(self, 'make_random_%s' % field.name):
				value = getattr(self, 'make_random_%s' % field.name)()
			else:
				if isinstance(field, models.SlugField):
					value = slugify(lorem_ipsum.words(2, False))
				elif isinstance(field, models.CharField):
					value = lorem_ipsum.words(5, False).capitalize()
				elif isinstance(field, models.TextField):
					value = lorem_ipsum.words(20).capitalize()
				elif isinstance(field, models.IntegerField):
					value = random.randint(1, 500)
				elif isinstance(field, models.ForeignKey):
					if not field.null:
						value = self.make_example_object(field.rel.to)
					else:
						continue
				elif isinstance(field, models.BooleanField):
					value = field.default
				elif isinstance(field, models.DateTimeField):
					value = datetime.utcnow().replace(tzinfo = utc)
				elif isinstance(field, models.DateField):
					value = datetime.utcnow().date().replace(tzinfo = utc)
				elif isinstance(field, models.FileField):
					value = 'filename.dat'
				elif isinstance(field, models.AutoField):
					continue
				elif isinstance(field, (models.ManyToManyField, models.fields.related.RelatedField)):
					continue
				else:
					raise Exception(
						'Don\'t know how to generate a default value for %s' % field
					)
			
			kwargs[field.name] = value
		
		return model(**kwargs)
Ejemplo n.º 11
0
	def render(self, context):
		try:
			count = int(self.count.resolve(context))
		except (ValueError, TypeError):
			count = 1
		if self.method == 'w':
			return words(count, common=self.common)
		if self.method == 's':
			return words(count, common=self.common).capitalize()
		if self.method == 't':
			return words(count, common=self.common).title()
		else:
			paras = paragraphs(count, common=self.common)
		if self.method == 'p':
			paras = ['<p>%s</p>' % p for p in paras]
		return u'\n\n'.join(paras)
Ejemplo n.º 12
0
    def get(self):
        self.room = self.get_param()
        # uid = uuid.uuid4().hex
        uid = lorem_ipsum.words(1, False).upper()
        self.me = uid
        data = dict(type='uid', uid=uid)
        data['from'] = uid
        self.send(data, event='uid')
        yield from self.validate_client()

        yield from self.publish(self.room, json.dumps((data, 'newbuddy')))

        self.schedule_heartbeat()
        logger.debug('New participant was published with uid={}'.format(uid))
        self.channel = yield from self.dispatcher.register(self.room)

        # Inside a while loop, wait for incoming events.
        while True:
            value = yield from self.channel.get()
            data, event = json.loads(value)
            sender = data.get('from', '')
            to = data.get('to', '')
            if sender == uid:
                continue
            if to and to != self.me:
                continue

            self.send(data, event=event)
            logger.info('Transmitted: %s from message chanel %s', repr(event), self.room)
Ejemplo n.º 13
0
class MovieFactory(factory.Factory):
    FACTORY_FOR = models.Movie

    title = factory.Sequence(lambda n: 'Movie%03d %s' % (int(n) + 1, words(2)))
    image = factory.Sequence(random_cover)

    short_description = factory.Sequence(lambda n: 'Movie%03d is %s' %
                                         (int(n) + 1, sentence()))
    description = factory.Sequence(lambda n: 'We can Movie%03d as %s' %
                                   (int(n) + 1, paragraph()))
    studio = factory.SubFactory(StudioFactory)

    played_times_day = factory.Sequence(
        lambda n: abs(int(n) + random.randint(5, 45)))
    played_times_month = factory.Sequence(
        lambda n: abs(int(n) + random.randint(150, 1500)))
    played_times_total = factory.Sequence(
        lambda n: abs(int(n) + random.randint(5000, 15000)))

    likes_day = factory.Sequence(lambda n: abs(int(n) + random.randint(0, 23)))
    likes_month = factory.Sequence(
        lambda n: abs(int(n) + random.randint(0, 750)))
    likes_total = factory.Sequence(
        lambda n: abs(int(n) + random.randint(0, 8000)))

    @factory.post_generation()
    def _create_movies(self, create, extracted, *args, **kwargs):
        for i in range(random.randint(2, 4)):
            trailer = TrailerFactory(movie=self)
            trailer.save()
Ejemplo n.º 14
0
def bootstrap():
    # Create some songs on the toplist
    Song.objects.get_or_create(title='Danger Zone',
        artist='Kenny Loggins',
        popularity=30,
        ready=True,
    )
    Song.objects.get_or_create(title='Radioactive',
        artist='Imagine Dragons',
        ready=True,
        votes=2,
    )
    Song.objects.get_or_create(title='Better Off Alone',
        artist='Alice Deejay',
        popularity=50,
        votes=3,
        ready=True,
    )

    # Create some random filler songs
    for i in range(41):
        Song.objects.get_or_create(
            artist='Artist %d' % i,
            ready=True,
            defaults={
                'popularity': random.randint(0, 100),
                'title': ' '.join(random.sample(words(40).split(), random.randint(2, 5))).title(),
            }
        )

    # Create some new song suggestions
    Song.objects.get_or_create(title='The Bumpi Song',
        artist='Spritney Bears',
    )
Ejemplo n.º 15
0
 def create_sample_blog_entries(klass, count=50):
     """
     Create N number of sample blog entries where N = the count parameter.
     Text in posts till be random lorem ipsum text. Author will be a 
     randomly selected author from the system, and date will be a random date
     from the last 2 years. All test entries will be marked "published".
     """
     klass._setup(BlogEntry, count)
     while count > 0:
         headline = words(randrange(3,12), common=False).capitalize()
         slug = klass._check_slug(slugify(headline)[:klass.field_len])
         b = BlogEntry(
             headline = headline,
             slug = slug,
             intro = klass._join_paras(
                 paragraphs(randrange(1,3), common=False)
             ),
             body = klass._join_paras(
                 paragraphs(randrange(2,5), common=False)
             ),
             pub_date = klass._get_rand_date(),
             status = BloggingSettings.PUBLISHED_ENTRY_STATES[0],
             author = Author.objects.order_by('?')[0]
         )
         b.save()
         count += -1
Ejemplo n.º 16
0
class WidgetFactory(factory.django.DjangoModelFactory):
    FACTORY_FOR = 'widgets.Widget'
    FACTORY_DJANGO_GET_OR_CREATE = ('title', 'template')

    title = factory.LazyAttribute(lambda o: words(2, common=False).title())
    text = factory.LazyAttribute(lambda o: str(paragraphs(1, common=False)))
    template = factory.SubFactory(WidgetTemplateFactory)
Ejemplo n.º 17
0
    def words(self, min_words=1, max_words=5):
        """Random text with 1 word."""

        if min_words > max_words:
            raise ParameterError('min_words greater than max_words')

        words = random.randint(min_words, max_words)
        return lorem_ipsum.words(words, common=False)
Ejemplo n.º 18
0
def lorem_ipsum(word_count):
    """
    Generates a 'lorem ipsum' string of the specified length in words.
    
    :param words: number of words to generate
    :return: string
    """
    return words(word_count, common=False)
Ejemplo n.º 19
0
class NewsFactory(factory.Factory):
    FACTORY_FOR = models.NewsItem

    title = factory.Sequence(lambda n: 'Hot news %03d %s' %
                             (int(n) + 1, words(2)))
    full_text = factory.Sequence(lambda n: 'Is going to be %03d %s' %
                                 (int(n) + 1, paragraphs(3)))

    image = factory.Sequence(random_cover)
Ejemplo n.º 20
0
 def _generate_unique(self, min_words, max_words, capitalize_first_character):
     for _ in range(10000):
         words_count = random.randint(min_words, max_words)
         value = '\n\n'.join(lorem_ipsum.words(words_count, common=False))
         if capitalize_first_character:
             value = '%s%s' % (value[0].upper(), value[1:])
         if value not in self.generated:
             self.generated.append(value)
             return value
Ejemplo n.º 21
0
 def _generate_unique(self, min_words, max_words, capitalize_first_character):
     for _ in range(10000):
         words_count = random.randint(min_words, max_words)
         value = "\n\n".join(lorem_ipsum.words(words_count, common=False))
         if capitalize_first_character:
             value = "%s%s" % (value[0].upper(), value[1:])
         if value not in self.generated:
             self.generated.append(value)
             return value
Ejemplo n.º 22
0
	def handle(self, *args, **options):
		call_command('reset', 'events', 'auth', interactive=False)
		
		print 'Creating test users...',
		# Create users
		test_user = User.objects.create(username="******", password="******", first_name="Patrick", last_name="Burt")
		print 'done'
		
		print 'Creating calendars for test users...',
		# Create calendars
		cal = test_user.owned_calendars.create(name="Test Calendar")
		print 'done'
		
		print 'Creating events for new calendars...',
		tag_choices = map(
			lambda t: Tag.objects.create(name=t),
			set(lorem_ipsum.words(20, False).lower().split())
		)
		contact_name_choices  = (None, 'Spork Belvadere', 'Captain ImABadGuy', 'Bill Paxton', 'Admiral Evildude')
		contact_phone_choices = (None, '407-123-3215', '563-456-4123', '123-456-4448')
		contact_email_choices = (None, '*****@*****.**', '*****@*****.**', '*****@*****.**')
		location_choices = (
			Location.objects.create(name="Student Union"),
			Location.objects.create(name="Library"),
			Location.objects.create(name="Arena"),
			Location.objects.create(name="Visual Arts Building"),
			Location.objects.create(name="Patrick's House"),
		)
		for i in range(1, 8):
			hour    = randint(8, 20)
			minutes = choice([15, 30, 45, 0, 0, 0])
			start   = datetime(datetime.now().year, 1, i, hour, minutes)
			end     = start + timedelta(hours=choice([1, 2, 3, 24, 25, 26, 48, 49, 50]))
			
			tags = list()
			for j in range(0, randint(1, 5)):
				tags.append(choice(tag_choices))
			
			event = cal.events.create(
				title=lorem_ipsum.words_cust(),
				description=lorem_ipsum.paragraph(),
				state=Event.Status.posted,
				owner=test_user,
				contact_name=choice(contact_name_choices),
				contact_phone=choice(contact_phone_choices),
				contact_email=choice(contact_email_choices)
			)
			event.tags.add(*tags)
			
			instance = event.instances.create(
				location=choice(location_choices),
				start=start,
				end=end,
				interval=EventInstance.Recurs.weekly,
				until=datetime(datetime.now().year + 1, 1, 1)
			)
		print 'done'
Ejemplo n.º 23
0
def generate():
    for user in User.objects.all():
        profile, created = Profile.objects.get_or_create(user = user,
            defaults=dict(
                name=user.get_full_name(),
                about=capfirst(words(8, common=False)) + '.',
            ),
        )
        print "Created User Profile: %s" % (profile,)
Ejemplo n.º 24
0
    def generate_CharField(self, **kwargs):
        """
		Generates char data for any CharField.
		Supported field extras:
		field_extras={
			'myfield':{
				'spaces':False|True, #(Default: True) #whether or not to allow spaces
				'word_count':3, #if specified, only 3 words will be generatd, if not specified, random between 1 and 4.
				'word_range:(2,5), #if specified, overrides the 'word_count' option, and will generate 2-5 random words.
			}
		}
		"""
        salt = ""
        field_extras = kwargs.get("field_extras", False)
        field = kwargs.get("field", ())
        if field.choices: return random.choice(field.choices)[0]
        if kwargs.get('unique', False):
            salt = "".join([
                random.choice(string.digits)
                for i in range(random.randint(1, 16))
            ])
        word_count = self._get_field_option(field_extras, 'word_count', -1)
        word_range = self._get_field_option(field_extras, 'word_range', -1)
        if isinstance(word_range, tuple) and len(word_range) > 1:
            result = "%s %s" % (words(random.randint(word_range[0],
                                                     word_range[1]),
                                      common=False), salt)
        elif word_count > 0:
            result = "%s %s" % (words(word_count, common=False), salt)
        else:
            result = "%s %s" % (words(random.randint(1, 4),
                                      common=False), salt)
        max_length = kwargs.get('max_length', None)
        length = len(result)
        if max_length and length > max_length:
            result = result[
                length - max_length:]  #chop off too many chars for max length
        if not self._get_field_option(
                field_extras, "spaces",
                True) and word_count == -1 and word_range == -1:
            result = result.replace(" ", "")
        result = re.sub(r' $', '', result)
        return result
Ejemplo n.º 25
0
def generate_address(field, instance, counter):
    # TODO: Replace this with a corpus of entertainingly varied 
    # (and possibly localised) addresses.
    country = "Australia"
    lorem = lorem_ipsum.words(3, common=False).title().split()
    lines = []
    lines.append('%d %s %s' % (random.randint(0,999), lorem[0], random.choice(("St", "Rd", "Crt", "Ave"))))
    lines.append('%s, %s %d' % (lorem[1], lorem[2], random.randint(1000, 9999)))
    lines.append(country)
    return '\n'.join(lines)
Ejemplo n.º 26
0
def setup_test_applicant_posts(test_applicants_pattern):
    """
    Sets up a certain number of test applicant posts.

    This method is EXACTLY the same as setup_test_job_posts, except it
    sets up ApplicantPosts instead of JobPosts, and that it randomly
    sets full_time_ and part_time as either True or False.  So see
    setup_test_job_posts for usage.
    """
    fake_applicant_ids = []
    for pattern in test_applicants_pattern:
        init_dict = {
            'first_name': lorem_ipsum.words(1, common=False),
            'last_name': lorem_ipsum.words(1, common=False),
            # shows what awful things phone number can accept... but
            # what can you do?  Stupid international numbers.
            'phone_number': lorem_ipsum.words(2, common=False),
            'email':
            '%s@%s.%s' % tuple(lorem_ipsum.words(3, common=False).split()),
            'position': random.choice(models.Position.objects.all()),
            'resume': '\n'.join(lorem_ipsum.paragraphs(4, common=False)),
            'when_posted': datetime.datetime.now()
        }

        init_dict['full_time'] = random.choice((True, False))
        init_dict['part_time'] = random.choice((True, False))

        init_dict['approved'] = pattern['approved']

        expiration_delta = datetime.timedelta(
            days=settings.JOBBOARD_POSTS_EXPIRE_DAYS)
        if pattern['expired']:
            init_dict['expiration_date'] = \
                datetime.date.today() - expiration_delta
        else:
            init_dict['expiration_date'] = \
                datetime.date.today() + expiration_delta

        new_applicantpost = models.ApplicantPost.objects.create(**init_dict)
        fake_applicant_ids.append(new_applicantpost.id)

    return fake_applicant_ids
Ejemplo n.º 27
0
    def test_post(self):
        response = self.retrieve(
            self.host + "comment/post/",
            object_pk=1,
            content_type="derrickpetzold.post",
            title=lorem.words(random.randint(3, 6), common=False),
            text=lorem.paragraph(),
        )

        assert response.success == True, "Post failed: %s" % (response.error)
        self.output.writeln("Post: Ok (%.2f)" % (response.run_time))
Ejemplo n.º 28
0
def generate_chars(field, instance, counter):
    """ Generates a 2-4 word title. """
    if 'phone' in field.name or 'mobile' in field.name or 'fax' in field.name:
        return generate_phone(field, instance, counter)
    if 'address' in field.name:
        return generate_address(field, instance, counter).splitlines()[0]
    max_length = int(field.max_length)
    if max_length < 15:
        length = random.randint(1, max_length)
        if 'number' in field.name or 'postcode' in field.name or 'zip' in field.name:
            return "".join([random.choice(string.digits) for i in range(length)])
        else:
            length = random.randint(1, max_length)
            return "".join([random.choice(string.ascii_letters) for i in range(length)])
    elif max_length < 25:
        return lorem_ipsum.words(1, common=False).title()[:max_length]
    elif max_length < 70:
        return lorem_ipsum.words(2, common=False).title()[:max_length]
    else:
        return lorem_ipsum.words(3, common=False).title()[:max_length]
Ejemplo n.º 29
0
def lipsum(words=None, paragraphs=None):
    from django.contrib.webdesign import lorem_ipsum
    if words is not None:
        return lorem_ipsum.words(words)
    elif paragraphs is not None:
        res = []
        for line in lorem_ipsum.paragraphs(paragraphs):
            res.append("<p>%s</p>" % (line))
        return "\n".join(res)
    else:
        return ""
Ejemplo n.º 30
0
def generate():
    for user in User.objects.all():
        for num_tweets in xrange(random.randint(1, 50)):
            num_words = random.randint(1, 100)
            content = words(num_words, common=False)
            oembed = random.choice(OEMBED_CONTENT)
            split_num = random.randint(0, len(content) - 1)
            content = capfirst('%s %s %s' % (content[:split_num], oembed, 
                content[split_num:]))[:139] + '.'
            tweet(user, content)
        print "Created %s Tweets from User: %s" % (num_tweets, user)
Ejemplo n.º 31
0
 def render(self, context):
     try:
         count = int(self.count.resolve(context))
     except (ValueError, TypeError):
         count = 1
     if self.method == 'w':
         return words(count, common=self.common)
     else:
         paras = paragraphs(count, common=self.common)
     if self.method == 'p':
         paras = ['<p>%s</p>' % p for p in paras]
     return u'\n\n'.join(paras)
Ejemplo n.º 32
0
def generate_address(field, instance, counter):
    # TODO: Replace this with a corpus of entertainingly varied
    # (and possibly localised) addresses.
    country = "Australia"
    lorem = lorem_ipsum.words(3, common=False).title().split()
    lines = []
    lines.append('%d %s %s' % (random.randint(
        0, 999), lorem[0], random.choice(("St", "Rd", "Crt", "Ave"))))
    lines.append('%s, %s %d' %
                 (lorem[1], lorem[2], random.randint(1000, 9999)))
    lines.append(country)
    return '\n'.join(lines)
Ejemplo n.º 33
0
    def test_published(self):

        headline = words(random.randint(5,10), common=False)

        a1, created = Article.objects.get_or_create( headline=headline,
            slug=slugify(headline),
            summary=sentence(),
            author=words(1,common=False),
            body=paragraphs(5),
            publish=True)

        a2, created = Article.objects.get_or_create( headline=headline,
            slug=slugify(headline),
            summary=sentence(),
            author=words(1,common=False),
            body=paragraphs(5),
            publish=False)


        published_articles = Article.objects.get_published()
        self.assertEqual(1, len(published_articles))
Ejemplo n.º 34
0
 def render(self, context):
     try:
         count = int(self.count.resolve(context))
     except (ValueError, TypeError):
         count = 1
     if self.method == "w":
         return words(count, common=self.common)
     else:
         paras = paragraphs(count, common=self.common)
     if self.method == "p":
         paras = ["<p>%s</p>" % p for p in paras]
     return "\n\n".join(paras)
Ejemplo n.º 35
0
def generate():
    for user in User.objects.all():
        profile, created = Profile.objects.get_or_create(user = user,
            defaults=dict(
                name = user.get_full_name(),
                about = capfirst(words(8, common=False)) + '.',
# @@@ need to move these to account fixtures
#                blogrss = random.choice(RSS_FEEDS),
#                timezone = random.choice(TIMEZONE_CHOICES)[0],
            ),
        )
        print "Created User Profile: %s" % (profile,)
Ejemplo n.º 36
0
def generate():
    for user in User.objects.all():
        for num_tweets in xrange(random.randint(1, 50)):
            num_words = random.randint(1, 100)
            content = words(num_words, common=False)
            oembed = random.choice(OEMBED_CONTENT)
            split_num = random.randint(0, len(content) - 1)
            content = capfirst(
                '%s %s %s' %
                (content[:split_num], oembed, content[split_num:]))[:139] + '.'
            Tweet.objects.create(sender=user, text=content)
        print "Created %s Tweets from User: %s" % (num_tweets, user)
Ejemplo n.º 37
0
def setup_test_applicant_posts(test_applicants_pattern):
    """
    Sets up a certain number of test applicant posts.

    This method is EXACTLY the same as setup_test_job_posts, except it
    sets up ApplicantPosts instead of JobPosts, and that it randomly
    sets full_time_ and part_time as either True or False.  So see
    setup_test_job_posts for usage.
    """
    fake_applicant_ids = []
    for pattern in test_applicants_pattern:
        init_dict = {
            'first_name': lorem_ipsum.words(1, common=False),
            'last_name': lorem_ipsum.words(1, common=False),
            # shows what awful things phone number can accept... but
            # what can you do?  Stupid international numbers.
            'phone_number': lorem_ipsum.words(2, common=False),
            'email': '%s@%s.%s' % tuple(
                lorem_ipsum.words(3, common=False).split()),
            'position': random.choice(models.Position.objects.all()),
            'resume': '\n'.join(lorem_ipsum.paragraphs(4, common=False)),
            'when_posted': datetime.datetime.now()}

        init_dict['full_time'] = random.choice((True, False))
        init_dict['part_time'] = random.choice((True, False))

        init_dict['approved'] = pattern['approved']

        expiration_delta = datetime.timedelta(days=settings.JOBBOARD_POSTS_EXPIRE_DAYS)
        if pattern['expired']:
            init_dict['expiration_date'] = \
                datetime.date.today() - expiration_delta
        else:
            init_dict['expiration_date'] = \
                datetime.date.today() + expiration_delta

        new_applicantpost = models.ApplicantPost.objects.create(**init_dict)
        fake_applicant_ids.append(new_applicantpost.id)

    return fake_applicant_ids
Ejemplo n.º 38
0
 def createRubbish(self, reply_chance=0.985):
     p = Post.objects.createRubbish()
     t = Topic(obj=p)
     for i in range(0, random.randint(0, 5)):
         t.tag(lorem_ipsum.words(random.randint(1, 2), False))
     if random.randint(0, 50) == 1:
         t.homepage = True
     t.deleted = p.deleted
     t.hidden = p.hidden
     t.save()
     while random.random() < reply_chance:
         t.replies.add(Post.objects.createRubbish())
     return t
Ejemplo n.º 39
0
def generate_chars(field, instance, counter):
    """ Generates a 2-4 word title. """
    if 'phone' in field.name or 'mobile' in field.name or 'fax' in field.name:
        return generate_phone(field, instance, counter)
    if 'address' in field.name:
        return generate_address(field, instance, counter).splitlines()[0]
    max_length = int(field.max_length)
    if max_length < 15:
        length = random.randint(1, max_length)
        if 'number' in field.name or 'postcode' in field.name or 'zip' in field.name:
            return "".join(
                [random.choice(string.digits) for i in range(length)])
        else:
            length = random.randint(1, max_length)
            return "".join(
                [random.choice(string.ascii_letters) for i in range(length)])
    elif max_length < 25:
        return lorem_ipsum.words(1, common=False).title()[:max_length]
    elif max_length < 70:
        return lorem_ipsum.words(2, common=False).title()[:max_length]
    else:
        return lorem_ipsum.words(3, common=False).title()[:max_length]
Ejemplo n.º 40
0
 def createRubbish(self, reply_chance=0.985):
     p = Post.objects.createRubbish()
     t = Topic(obj=p)
     for i in range(0, random.randint(0, 5)):
         t.tag(lorem_ipsum.words(random.randint(1, 2), False))
     if random.randint(0, 50) == 1:
         t.homepage = True
     t.deleted = p.deleted
     t.hidden = p.hidden
     t.save()
     while random.random() < reply_chance:
         t.replies.add(Post.objects.createRubbish())
     return t
Ejemplo n.º 41
0
def insert_docs (n, model=None) :
    if model is None :
        model = doc

    #print ">> Cleaning up models."
    # attach models

    cursor = connection.cursor()

    # drop table, if exists.
    sql = "DROP TABLE %s" % model._meta.db_table
    try :
        cursor.execute(sql)
    except :
        pass

    # create table
    sql, params = connection.creation.sql_create_model(model, no_style())
    cursor.execute(sql[0])

    #core.register(model, )

    #print ">> Inserting docs"
    d = list()
    for i in range(n) :
        d.append(
            model.objects.create(
                title=words(5, False),
                content=paragraphs(1, False)[0][:50],
                summary=paragraphs(1, False)[0][:50],
                time_added=datetime.datetime.now() - datetime.timedelta(days=int(random.random() * 10)),
                path="/home/dir.com/" + str(random.random() * 1000) + "/",
                email="%s@%s" % (words(1, False), words(1, False))
            )
        )
        #print "\t", d[-1]

    return d
Ejemplo n.º 42
0
    def handle(self, *args, **options):
        for i in xrange(74):
            title = lipsum.words(random.randint(1, 6))
            entry = Entry(
                title=title,
                teaser="\n".join(lipsum.paragraphs(random.randint(1, 3))),
                content="\n".join(lipsum.paragraphs(random.randint(12, 16))),
                created_at=timezone.now() - timedelta(
                    seconds=random.randint(0, 40000000)
                ),
                is_active=not getrandbits(1)
            )

            entry.save()
Ejemplo n.º 43
0
 def createRubbish(self, topic=None):
     """
     :return: Post
     """
     p = Post(topic=topic)
     p.title = lorem_ipsum.words(random.randint(0, 5), False)
     p.body = p.body_markup = "<br/>\n".join(lorem_ipsum.paragraphs(random.randint(0, 7), False))
     p.summary = lorem_ipsum.paragraph()
     p.user = User.objects.all()[random.randint(0, 850)]
     if random.randint(1, 50) == 1:
         p.hidden = True
     if random.randint(1, 100) == 1:
         p.deleted = True
     return p
Ejemplo n.º 44
0
 def createRubbish(self, topic=None):
     """
     :return: Post
     """
     p = Post(topic=topic)
     p.title = lorem_ipsum.words(random.randint(0, 5), False)
     p.body = p.body_markup = "<br/>\n".join(lorem_ipsum.paragraphs(random.randint(0, 7), False))
     p.summary = lorem_ipsum.paragraph()
     p.user = User.objects.all()[random.randint(0, 850)]
     if random.randint(1, 50) == 1:
         p.hidden = True
     if random.randint(1, 100) == 1:
         p.deleted = True
     return p
Ejemplo n.º 45
0
def insert_docs(n, model=None):
    if model is None:
        model = doc

    #print ">> Cleaning up models."
    # attach models

    cursor = connection.cursor()

    # drop table, if exists.
    sql = "DROP TABLE %s" % model._meta.db_table
    try:
        cursor.execute(sql)
    except:
        pass

    # create table
    sql, params = connection.creation.sql_create_model(model, no_style())
    cursor.execute(sql[0])

    #core.register(model, )

    #print ">> Inserting docs"
    d = list()
    for i in range(n):
        d.append(
            model.objects.create(
                title=words(5, False),
                content=paragraphs(1, False)[0][:50],
                summary=paragraphs(1, False)[0][:50],
                time_added=datetime.datetime.now() -
                datetime.timedelta(days=int(random.random() * 10)),
                path="/home/dir.com/" + str(random.random() * 1000) + "/",
                email="%s@%s" % (words(1, False), words(1, False))))
        #print "\t", d[-1]

    return d
Ejemplo n.º 46
0
    def items(self, create, extracted, **kwargs):

        if not extracted:
            return

        if randint(0, 5) >= 3:
            self.show_description = True

        if randint(0, 5) >= 3:
            self.required = True

        for item in extracted:
            if self.show_description:
                item.description = '\r\n\r\n  '.join(words(randint(2, 7), True))
            self.translates.add(item)
Ejemplo n.º 47
0
def get_recipe():
    INGREDIENTS = Food.objects.exclude(id__in=INGREDIENTS_TOP).order_by('?').values_list('name', flat=True)[:random.randint(2, 10)]
    return {
        'ingredients': INGREDIENTS,
        'summary': '\n\n'.join(lorem_ipsum.paragraphs(random.randint(0, 2), False)),
        'name': lorem_ipsum.words(random.randint(2, 6), False).title(),
        'difficulty': random.choice(Recipe.DIFFICULTY_CHOICES)[0],
        'category': random.choice(CATEGORIES),
        'servings': random.choice(SERVINGS),
        'prep_minutes': random.choice(range(10, 150, 5)),
        'inactive_prep_minutes': random.choice(range(0, 150, 5)),
        'cook_minutes': random.choice(range(10, 150, 5)),
        'language': random.choice(LANGUAGES),
        'is_private': random.choice([True, False])
    }
Ejemplo n.º 48
0
 def generate(self):
     from django.contrib.webdesign.lorem_ipsum import paragraphs, sentence, \
         words
     if self.method == 'w':
         lorem = words(self.count, common=self.common)
     elif self.method == 's':
         lorem = u' '.join([sentence() for i in xrange(self.count)])
     else:
         paras = paragraphs(self.count, common=self.common)
         if self.method == 'p':
             paras = ['<p>%s</p>' % p for p in paras]
         lorem = u'\n\n'.join(paras)
     if self.max_length:
         length = random.randint(self.max_length / 10, self.max_length)
         lorem = lorem[:max(1, length)]
     return lorem.strip()
Ejemplo n.º 49
0
class PositionFactory(factory.django.DjangoModelFactory):
    FACTORY_FOR = 'positions.Position'
    FACTORY_DJANGO_GET_OR_CREATE = ('title', )

    title = factory.LazyAttribute(lambda o: words(2, common=False).title())

    @factory.post_generation
    def links(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of groups were passed in, use them
            for link in extracted:
                self.links.add(link)
Ejemplo n.º 50
0
class PrelectionFactory(factory.DjangoModelFactory):
    FACTORY_FOR = Prelection

    main_prelector = factory.SubFactory(ParticipantFactory)
    conference = factory.SubFactory(ConferenceFactory)
    title = factory.LazyAttribute(lambda o: words(5, False)[:50])
    description = factory.LazyAttribute(lambda o: paragraph())
    length = 60

    @factory.post_generation
    def other_prelectors(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            for prelector in extracted:
                self.other_prelectors.add(prelector)
Ejemplo n.º 51
0
    def testCreateObject (self) :
        o = models_tests.doc.objects.create(
            title=words(5, False),
            content=paragraphs(1, False)[0],
            summary=paragraphs(1, False)[0],
            time_added=datetime.datetime.now() - datetime.timedelta(days=int(random.random() * 10)),
            path="/home/dir.com/" + str(random.random() * 1000) + "/",
        )

        o_n = self.from_indexed.get(pk=o.pk)

        self.assertEquals(o.pk, o_n.pk)
        self.assertEquals(o.title, o_n.title)
        self.assertEquals(o.summary, o_n.summary)
        self.assertEquals(
            document.Fields.DateTime("date").to_index(o.time_added)[0][0],
            document.Fields.DateTime("date").to_index(o_n.time_added)[0][0]
        )
Ejemplo n.º 52
0
def generate():
    num_users = User.objects.all().count()
    for user in User.objects.all():
        pre_friend_ids = [
            i['friend'].id for i in Friendship.objects.friends_for_user(user)
        ]
        num = random.randint(1, (num_users - 1) / 10)
        friends = User.objects.exclude(
            id__in=pre_friend_ids).order_by('?')[:num]
        for friend in friends:
            num_words = random.randint(1, 100)
            message = words(num_words, common=False)
            ji = FriendshipInvitation.objects.create(from_user=user,
                                                     to_user=friend,
                                                     message=message,
                                                     status='2')
            ji.accept()
        print "Created Friendship Between %s and %d others." % (user,
                                                                len(friends))
Ejemplo n.º 53
0
class StudioFactory(factory.Factory):
    FACTORY_FOR = models.MovieStudio

    title = factory.Sequence(lambda n: 'Studio%03d %s' %
                             (int(n) + 1, words(2)))
    logo = factory.Sequence(random_logo)

    @factory.post_generation()
    def _create_movies(self, create, extracted, *args, **kwargs):
        for i in range(random.randint(2, 4)):
            movie = MovieFactory(studio=self)
            movie.save()

    @factory.post_generation()
    def _create_motivation(self, create, extracted, *args, **kwargs):
        info = StudioMotivationInfoFactory(studio=self)
        info.save()
        progress = StudioMotivationProgressFactory(info=info)
        progress.save()
Ejemplo n.º 54
0
class TranslationFactory(factory.DjangoModelFactory):
    FACTORY_FOR = DraftTranslation

    # todo: lorem ipsum
    article = factory.SubFactory(ArticleFactory)
    author = factory.SubFactory(UserFactory)
    title = factory.LazyAttribute(lambda o: words(randint(1, 3), False)[:50])
    slug = factory.LazyAttribute(
        lambda o: o.title.replace(' ', '-').lower()[:20]
    )

    @factory.lazy_attribute
    def text(self):
        return '\r\n\r\n  '.join(paragraphs(randint(2, 4), True))

    @factory.post_generation
    def published(self, created, extracted, **kwargs):
        if extracted:
            self.publish()
Ejemplo n.º 55
0
    def load_sequences(self):
        """Load example sequences"""
        LOGGER.info(u" > sequences...")
        resource_list = \
            self.research_project_collection_1.collection.resources.all()
        for counter in xrange(5):
            resources = random.sample(resource_list, random.randint(1, 5))

            sequence = Sequence.objects.create(
                sequence_id="S-{no}".format(no=counter),
                description=words(10),
                collection=self.classification_project_collection_1,
                created_at=Command._get_random_datetime(),
                created_by=self.users['alice']
            )
            for resource in resources:
                SequenceResourceM2M.objects.create(
                    sequence=sequence,
                    resource=resource
                )
Ejemplo n.º 56
0
def bootstrap():
    # Create some songs on the toplist
    Song.objects.get_or_create(
        title='Danger Zone',
        artist='Kenny Loggins',
        popularity=30,
        ready=True,
    )
    Song.objects.get_or_create(
        title='Radioactive',
        artist='Imagine Dragons',
        ready=True,
        votes=2,
    )
    Song.objects.get_or_create(
        title='Better Off Alone',
        artist='Alice Deejay',
        popularity=50,
        votes=3,
        ready=True,
    )

    # Create some random filler songs
    for i in range(41):
        Song.objects.get_or_create(artist='Artist %d' % i,
                                   ready=True,
                                   defaults={
                                       'popularity':
                                       random.randint(0, 100),
                                       'title':
                                       ' '.join(
                                           random.sample(
                                               words(40).split(),
                                               random.randint(2, 5))).title(),
                                   })

    # Create some new song suggestions
    Song.objects.get_or_create(
        title='The Bumpi Song',
        artist='Spritney Bears',
    )
Ejemplo n.º 57
0
 def test_words(self):
     self.assertEqual(words(7),
                      'lorem ipsum dolor sit amet consectetur adipisicing')
Ejemplo n.º 58
0
 def _generate(self, min_words, max_words, capitalize_first_character):
     words_count = random.randint(min_words, max_words)
     result = lorem_ipsum.words(words_count, common=False)
     if capitalize_first_character:
         return '%s%s' % (result[0].upper(), result[1:])
     return result