def generate_TextField(self, **kwargs): """ Generates text data for any TextField. Supported field extras: field_extras={ 'myfield':{ 'spaces':False|True, #(Default: True) #whether or not to allow spaces 'paragraph_count':3, #The number of paragraphs to generate. 'paragraph_range':(2,8) #A range for the number of paragraphs to generate - random between this range. } } """ field_extras = kwargs.get("field_extras", False) paragraph_count = self._get_field_option(field_extras, 'paragraph_count', -1) paragraph_range = self._get_field_option(field_extras, 'paragraph_range', -1) if isinstance(paragraph_range, tuple) and len(paragraph_range) > 1: result = "\n".join( paragraphs( random.randint(paragraph_range[0], paragraph_range[1]))) elif paragraph_count > 0: result = "\n".join(paragraphs(paragraph_count)) else: result = "\n".join(paragraphs(random.randint(1, 3))) if not self._get_field_option(field_extras, 'spaces', True): result = result.resplace(" ", "") result = re.sub(r' $', '', result) return result
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
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() )
def test_create(self): self.client.login(username='******', password='******') response = self.client.get(reverse('presscenter:admin:create')) self.assertEqual(response.status_code, 200) response = self.client.post( reverse('presscenter:admin:create'), { 'announce': paragraphs(5), 'title': 'test doc 1', 'site': Site.objects.get_current().id, 'pub_date': self.pub_date.strftime("%Y-%m-%d %H:%M") }) self.assertEqual(response.status_code, 200) self.assert_("Dublicate document title in the same publication date." in response.content) response = self.client.post( reverse('presscenter:admin:create'), { 'announce': paragraphs(5), 'title': 'test article title', 'site': Site.objects.get_current().id, 'pub_date': self.pub_date.strftime("%Y-%m-%d %H:%M") }) self.assertEqual(response.status_code, 302) self.assert_( Document.objects.get(title='test article title', pub_date=self.pub_date))
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()))
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
def test_get_meta_description(self): title = DocumentTitleDEFactory(description='ä "description"') self.assertEqual(title.get_meta_description(), title.description.replace('"', '"')) title.description = paragraphs(1)[0] self.assertEqual(title.get_meta_description(), paragraphs(1)[0][:160]+'...') title.meta_description = paragraphs(1)[0] self.assertEqual(title.get_meta_description(), paragraphs(1)[0])
def test_get_meta_description(self): title = EventTitleFactory(description='ä "description"') self.assertEqual(title.get_meta_description(), title.description.replace('"', '"')) title.description = paragraphs(1)[0] self.assertEqual(title.get_meta_description(), paragraphs(1)[0][:160]+'...') title.meta_description = paragraphs(1)[0] self.assertEqual(title.get_meta_description(), paragraphs(1)[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()
def lorem(randseed=None, count=1, method=None): u""" Creates Lorem Ipsum text. Usage format: {% lorem [randseed] [count] [method] %} ``randseed`` is any hashable object used to initialize the random numbers generator. If ``randseed`` is not given the common "Lorem ipsum dolor sit..." text is used. ``count`` is a number of paragraphs or sentences to generate (default is 1). ``method`` is either ``p`` for HTML paragraphs enclosed in ``<p>`` tags, or ``b`` for plain-text paragraph blocks (default is ``b``). Notice: This filter is rewrited ``lorem`` filter from ``webdesign`` modul from default Django package ``django.contrib.webdesign``. The original ``lorem`` filter does not give stable random text, thus its generated paragraphs change on every page refresh. We stabilize the generated text by setting a fixed randseed before generating the paragraph. """ state = random.getstate() random.seed(randseed) res = paragraphs(count, common=(randseed is None)) random.setstate(state) if method == u'p': res = [u'<p>{}</p>'.format(p) for p in res] return u'\n'.join(res)
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)
def sample_letter(): to_addr_lines = ['Some Person', '123 Fake St', 'Vancouver, BC, Canada'] from_name_lines = ['Greg Baker', 'Lecturer, School of Computing Science'] signer = Person.objects.get(userid="ggbaker") letter = LetterContents(to_addr_lines=to_addr_lines, from_name_lines=from_name_lines, signer=signer) letter.add_paragraphs(paragraphs(random.randint(5,15))) return letter
def paragraphs(self, min_paragraphs=1, max_paragraphs=5): """Random text with variable number of words, several sentences.""" if min_paragraphs > max_paragraphs: raise ParameterError('min_paragraphs greater than max_paragraphs') return "\n\n".join(lorem_ipsum.paragraphs(random.randrange(min_paragraphs, max_paragraphs+1)))
def _generate_unique(self, min_paragraphs, max_paragraphs): for _ in range(10000): paragraphs_count = random.randint(min_paragraphs, max_paragraphs) value = '\n\n'.join(lorem_ipsum.paragraphs(paragraphs_count, common=False)) if value not in self.generated: self.generated.append(value) return value
def any_text_field(field, **kwargs): """ Return random 'lorem ipsum' Latin text >>> result = any_field(models.TextField()) >>> type(result) <type 'str'> """ return str("\n".join(paragraphs(10)))
def get_context(self, context): context = super(DummyPanel, self).get_context(context) context.update({ 'header': _("Dummy panel"), 'content': '\n\n'.join(lorem_ipsum.paragraphs(random.randint(1, 1))), }) return context
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] )
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)
def any_text_field(field, **kwargs): """ Return random 'lorem ipsum' Latin text >>> result = any_field(models.TextField()) >>> from django.contrib.webdesign.lorem_ipsum import COMMON_P >>> result[0] == COMMON_P True """ return str(paragraphs(10))
def any_text_field(field, **kwargs): """ Return random 'lorem ipsum' Latin text >>> result = any_field(models.TextField()) >>> from django.contrib.webdesign.lorem_ipsum import COMMON_P >>> result[0] == COMMON_P True """ return paragraphs(10)
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 ""
def test_new_post(self): dct = dict( author=choice(User.objects.filter(is_active=True)), content="\n".join(lorem_ipsum.paragraphs(randint(10, 20))), title="teste 1", ) p = Post(**dct) p.save()
class ChapterFactory(factory.DjangoModelFactory): class Meta: model = Chapter version = factory.SubFactory(BookVersionFactory) book = factory.SubFactory(BookFactory) url_title = factory.Sequence(lambda n: 'chapter-%d' % n) title = factory.Sequence(lambda n: 'Chapter %d' % n) status = factory.SubFactory(BookStatusFactory) content = paragraphs(4)
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)
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)
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))
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
def _create_test_post(slug, time_delta): from google.appengine.ext import db from django.contrib.webdesign import lorem_ipsum from datetime import datetime p = Post( title="Happy happy", body=(2 * "\n").join(lorem_ipsum.paragraphs(4)), # user = users.get_current_user(), tags=[db.Category("bonners"), db.Category("cheese"), db.Category("weiners")], slug=slug, published_at=datetime.fromtimestamp(1282380470 - time_delta), ) p.put()
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
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
def create(dir=None): """Creates a "filesystem" in a new temp dir and creates one file in it.""" if not dir: dir = tempfile.mkdtemp() logger.info("Using %s as base dir." % dir) fs = LocalSubFileSystem(dir) def write(path, contents): f = fs.open(path, "w") f.write(contents) f.close() write("/hello.txt", "hello world\n") write("/goodbye.txt", "goodbyte\n") write("/xss.html", "<blink>escape!!!</blink><script>alert('hello')</script>\n") write("/evil path%-of&doom?.txt", "annoying, eh?\n") # no </script> tag in filename, since that's a path delimiter. write("/xsspath<i><script>alert('hello').txt", "definitely annoying.\n") # But we can do </script> as a multi-directory thing! fs.mkdir("/<script>alert('hello')<") write("/<script>alert('hello')</script>", "there") fs.mkdir("/sub?dir") write("/sub?dir/howdy.txt", "there\n") fs.mkdir("/bigfiles") write("/bigfiles/loremipsum.txt", "\n\n".join(lorem_ipsum.paragraphs(1000))) # 50K of dev random write("/bigfiles/random_binary.bin", open("/dev/urandom").read(1024 * 50)) write("/count", "0123456789" * 8) write("/chmod-unreadable", "") fs.chmod("/chmod-unreadable", 0000) write("/chown-staff-group", "") try: stats = fs.stats("/chown-staff-group") # Figure out a group id that is different from the one it already has cur_gid = grp.getgrnam(stats["group"]).gr_gid other_groups = [gid for gid in os.getgroups() if gid != cur_gid] new_gid = other_groups[0] fs.chown("/chown-staff-group", fs.stats("/chown-staff-group")["user"], grp.getgrgid(new_gid).gr_name) except OSError: logger.exception("Ignoring error.") return fs
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]) }
def generate_TextField(self,**kwargs): """ Generates text data for any TextField. Supported field extras: field_extras={ 'myfield':{ 'spaces':False|True, #(Default: True) #whether or not to allow spaces 'paragraph_count':3, #The number of paragraphs to generate. 'paragraph_range':(2,8) #A range for the number of paragraphs to generate - random between this range. } } """ field_extras=kwargs.get("field_extras",False) paragraph_count=self._get_field_option(field_extras,'paragraph_count',-1) paragraph_range=self._get_field_option(field_extras,'paragraph_range',-1) if isinstance(paragraph_range,tuple) and len(paragraph_range)>1: result="\n".join(paragraphs(random.randint(paragraph_range[0],paragraph_range[1]))) elif paragraph_count > 0: result="\n".join(paragraphs(paragraph_count)) else: result="\n".join(paragraphs(random.randint(1,3))) if not self._get_field_option(field_extras,'spaces',True): result=result.resplace(" ","") result=re.sub(r' $','',result) return result
def create_blog_entries(self): blog_entry_list = [] for i in range(self.config['BLOG']): title = lorem_ipsum.sentence() markdown = '\n\n'.join(lorem_ipsum.paragraphs(random.randint(1, 3))) blog_entry = BlogEntry( title=title, slug=slugify(title), markdown=markdown, html=convert_markdown(markdown), created_by=self.user, ) blog_entry_list.append(blog_entry) BlogEntry.objects.bulk_create(blog_entry_list)
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()
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()
def test_edit(self): self.client.login(username='******', password='******') response = self.client.get( reverse('presscenter:admin:edit', args=[self.doc.id])) self.assertEqual(response.status_code, 200) response = self.client.post( reverse('presscenter:admin:edit', args=[self.doc.id]), { 'announce': paragraphs(5), 'title': 'test article title', 'site': Site.objects.get_current().id, 'pub_date': self.pub_date.strftime("%Y-%m-%d %H:%M") }) self.assertEqual(response.status_code, 200)
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 range(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()
def create(dir=None): """Creates a "filesystem" in a new temp dir and creates one file in it.""" if not dir: dir = tempfile.mkdtemp() logger.info("Using %s as base dir." % dir) fs = LocalSubFileSystem(dir) def write(path, contents): f = fs.open(path, "w") f.write(contents) f.close() write("/hello.txt", "hello world\n") write("/goodbye.txt","goodbyte\n") write("/xss.html","<blink>escape!!!</blink><script>alert('hello')</script>\n") write("/evil path%-of&doom?.txt", "annoying, eh?\n") # no </script> tag in filename, since that's a path delimiter. write("/xsspath<i><script>alert('hello').txt", "definitely annoying.\n") # But we can do </script> as a multi-directory thing! fs.mkdir("/<script>alert('hello')<") write("/<script>alert('hello')</script>", "there") fs.mkdir("/sub?dir") write("/sub?dir/howdy.txt", "there\n") fs.mkdir("/bigfiles") write("/bigfiles/loremipsum.txt", "\n\n".join(lorem_ipsum.paragraphs(1000))) # 50K of dev random write("/bigfiles/random_binary.bin", open("/dev/urandom").read(1024*50)) write("/count", "0123456789"*8) write("/chmod-unreadable", "") fs.chmod("/chmod-unreadable", 0000) write("/chown-staff-group", "") try: stats = fs.stats("/chown-staff-group") # Figure out a group id that is different from the one it already has cur_gid = grp.getgrnam(stats["group"]).gr_gid other_groups = [gid for gid in os.getgroups() if gid != cur_gid] new_gid = other_groups[0] fs.chown("/chown-staff-group", fs.stats("/chown-staff-group")["user"], grp.getgrgid(new_gid).gr_name) except OSError: logger.exception("Ignoring error.") return fs
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
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
def create_single_rubbish(self, reply_choice=0.9): p = Post() 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 = get_user_model().objects.get(pk=random.choice(self.userids)) p.posted_by = p.user.username p.rating = random.randint(1, 30) #Trying to get a slightly more realistic rating distribution if p.rating <= 2: p.rating = random.randint(-5, 0) elif p.rating <= 20: p.rating /= 2 else: p.rating -= 18 if p.rating > 5 and random.randint(1, 20) == 1: p.homepage = True if p.rating < 1 and random.randint(1, 10) == 1: p.hidden = True if p.rating == -1 and random.randint(1, 10) == 1: p.deleted = True p.save() p.replies_count = 0 while random.random() < reply_choice: p.replies.add(Post.objects.create_single_rubbish(reply_choice=reply_choice / 5)) p.replies_count += 1 if p.replies_count != 0: p.save() # tags = random.randint(0, 3) # tagscount = Tag.objects.count() # if tagscount > 0: # for i in range(0, tags): # TaggedObject.objects.get_or_create(tag=Tag.objects.get(pk=random.randint(1, tagscount)), # object_id=p.pk, # content_type=ContentType.objects.get_for_model(Post)) return p
def get(self, request, *args, **kwds): context = self.get_context_data() _id = request.GET['id'] if _id.isdigit() and int(_id) in self.VALID_IDS: parag = int((int(_id) - 20) * 4) # A bad thing about the lorem_ipsum module is that it will generate # RANDOM texts each time we call it, that means that in some cases # the plugin will detect big changes, and in some others it won't. # # To be able to fix this issue, we set the random seed # # Keep in mind that with some seeds the test will PASS, and with # many others it won't. Lucky me, it passed on the second try. random.seed(1) context['html'] = '<br><br>'.join(lorem_ipsum.paragraphs(parag)) else: raise Http404 return render(request, self.template_name, context)
def load_data(): site = Site.objects.all()[0] site.name = site.domain = "www.example.com" site.save() # photologue at = PhotoSize.objects.get_or_create(name='admin_thumbnail', width=80) display = PhotoSize.objects.get_or_create(name='display', width=400) fullsize = PhotoSize.objects.get_or_create(name='fullsize', width=800) thumbnail = PhotoSize.objects.get_or_create(name='thumbnail', width=100) photos = [] for word in "make an image for each word in this sentence".split(): ifn = generate_image(word) photo, created = Photo.objects.get_or_create(title=word, title_slug=slugify(word), is_public=True, caption=words(5)) photo.image.save(os.path.basename(ifn), ContentFile(open(ifn, 'rb').read())) photos.append(photo) # create 40 articles for i in range(1, 40): headline = words(random.randint(5,10), common=False) a, created = Article.objects.get_or_create( headline=headline, slug=slugify(headline), author=words(1,common=False), body=paragraphs(5), publish=True) section, created = Section.objects.get_or_create(title=words(1,common=False)) a.sections.add(section) a.save() for j in range(0, random.randint(0, 5)): a.photos.add(photos[j])
def _generate(self, min_paragraphs, max_paragraphs): paragraphs_count = random.randint(min_paragraphs, max_paragraphs) return '\n\n'.join(lorem_ipsum.paragraphs(paragraphs_count, common=False))
def test_paragraphs(self): self.assertEqual(paragraphs(1), [ 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' ])
def text(self): return '\r\n\r\n '.join(paragraphs(randint(2, 4), True))
def bootstrap(): johnny, _ = User.objects.get_or_create(username='******', first_name='Johnny', last_name='Dev') pedro, _ = User.objects.get_or_create(username='******', first_name='Pedro', last_name='Trenersjef') Article.objects.get_or_create( title='Ny funksjonalitet på nettsidene oppe snart', content='''<p> Masse nye spennende greier på vei, dette blir kult. </p> <h2>Nye greier</h2> <p>Noen av de nye greiene som kommer er:</p> <ul> <li>Awesomeness</li> <li>Kule ting</li> <li>Buzzwords</li> <li>Puddergaranti</li> </ul> <p> Håper endringene faller i smak! </p>''', author=johnny, defaults={ 'published_date': now(), }) Article.objects.get_or_create(title='Trening starter på igjen NÅ!', content='''<p> Mandagstrening is back in the groove, snakkes på i-bygget! </p> <p> Se treningssiden for mer info hvis du trenger det, men dette burde dekke det meste. </p>''', author=pedro, defaults={ 'published_date': (now() - timedelta(days=1)), }) for i in range(15): Article.objects.get_or_create(title='Tilfeldig sluddervarv #%d' % i, author=johnny, defaults={ 'published_date': (now() - timedelta(days=(2 + i))), 'content': ''.join('<p>%s</p>' % p for p in paragraphs(3)), }) SubPageArticle.objects.get_or_create(title='Trening', slug='trening', content='''<p> Vi trener sånn innimellom, stort sett på mandager, stort sett i 20-tiden. </p> <p> Du finner oss i I-bygget på Gløs. </p>''', author=pedro, defaults={ 'published_date': (now() - timedelta(hours=3)), }) SubPageArticle.objects.get_or_create(title='Webutvikling', slug='webutvikling', content='''<p> Trenger stadig nye sjeler til å bidra med webutvikling, har du noe fornuftig å komme med er det bare å skrike ut. </p>''', author=johnny, defaults={ 'published_date': (now() - timedelta(hours=5)), })
def get_context(self, context): context.update({ 'header': _("Dummy panel"), 'content': '\n\n'.join(lorem_ipsum.paragraphs(random.randint(1, 3))), }) return context
log = logging.getLogger('dilla') dictionary = getattr(settings, 'DICTIONARY', "/usr/share/dict/words") if os.path.exists(dictionary) and \ not getattr(settings, 'DILLA_USE_LOREM_IPSUM', False): d = open(dictionary, "r").readlines() _random_words = \ lambda n: " ".join([random.choice(d).lower().rstrip() \ for i in range(n)]) _random_paragraph = lambda: _random_words(30).capitalize() _random_paragraphs = lambda n: \ ".\n\n".join([_random_paragraph() for i in range(n)]) else: _random_words = lorem_ipsum.words _random_paragraphs = lambda n: ".\n\n".join(lorem_ipsum.paragraphs(n)) @spam.global_handler('CharField') def random_words(record, field): # this is somewhat nasty, URLField.get_internal_type() # returns 'CharField' if isinstance(field, URLField): return "http://%s.com/%s/?%s=%s" % tuple(_random_words(4).split(" ")) max_length = field.max_length words = _random_words(3).decode('utf8').encode('utf8') if max_length < len(words): return words[:max_length] return words
def rand_text(cls, num_paragraphs=None): if not num_paragraphs: num_paragraphs = cls.rand_int(start=1, end=5) return lorem_ipsum.paragraphs(num_paragraphs, common=False)
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