def test_can_post_a_message(self): lexpagiens_link = self.selenium.find_element_by_link_text('Discussions') ActionChains(self.selenium).move_to_element(lexpagiens_link).perform() disconnect_link = self.selenium.find_element_by_link_text('Nouvelle discussion') disconnect_link.click() WebDriverWait(self.selenium, 1).until( lambda driver: driver.find_element_by_id('id_title')) # le Corbeau et le Renard, Jean de la Fontaine title = words(6, False) text = '\n'.join(paragraphs(5)) title_input = self.selenium.find_element_by_name('title') title_input.send_keys(title) text_input = self.selenium.find_element_by_name('text') text_input.send_keys(text) self.selenium.find_element_by_css_selector('.fa.fa-bold').click() text_input.send_keys('Et du GRAS!') for i in range(len('[/b]')): text_input.send_keys(Keys.RIGHT) self.selenium.find_element_by_css_selector('.fa.fa-italic').click() text_input.send_keys('Et de l\'italique!') for i in range(len('[/i]')): text_input.send_keys(Keys.LEFT) self.selenium.find_element_by_xpath('//button[text()="Poster"]').click() WebDriverWait(self.selenium, 1).until( lambda driver: driver.find_element_by_xpath('//h3[text()="%s"]' % title)) text_block = self.selenium.find_element_by_css_selector('.board-messagelist .message-text .bbcode') bbcode = '<b>Et du GRAS!</b><em>Et de l\'italique!</em>' formatted_message = '%s%s' % ('<br>'.join(text.split('\n')), bbcode) self.assertEqual(text_block.get_attribute('innerHTML').strip(), formatted_message)
def get_context_data(self, **kwargs): from django.utils.lorem_ipsum import paragraphs context = super(StaticPageView, self).get_context_data(**kwargs) context['static_text'] = paragraphs(10) return context
def handle(self, **options): if not User.objects.exists(): usernames = words(NUMBER_OF_USERS).split(" ") User.objects.bulk_create([ User(username=username, password=username, email="*****@*****.**" % username) for username in usernames ]) if not Tag.objects.exists(): Tag.objects.bulk_create([Tag(name=word) for word in WORDS]) if not Post.objects.exists(): users = list(User.objects.all()) tags = list(Tag.objects.all()) for p in range(NUMBER_OF_POSTS): post = Post.objects.create( author=choice(users), title=sentence(), body="\n".join(paragraphs(randint(3, 5))), thumbnail="http://test.com/test.jpg", is_published=choice([True, True, False]), ) post.tags.add(*sample(tags, randint(0, 10))) post.liked_by.add(*sample(users, randint(0, 10))) for i in range(comment_count()): Comment.objects.create( user=choice(users), body=paragraph(), post=post, parent=None if random() < 0.5 or not post.is_published else choice(post.comment_set.all() or [None]))
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 __init__(self, label, contact=None, body=None, **kw): super().__init__(label, **kw) self.contact = contact from django.utils.lorem_ipsum import sentence, paragraphs self.body = body or paragraphs(3) if not self.title: self.title = self.name.title() if not self.summary: self.summary = sentence().capitalize()
def randDoc(n): for i in range(n): d = { "rank": i + 1, "docno": docsid[i%len(docsid)], "title": words(5), "snippet": paragraphs(1)[0], } yield d
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 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 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 create_lecture(zosia, author): data = { 'zosia': zosia, 'info': lorem_ipsum.words(60)[:750], 'title': lorem_ipsum.sentence()[:255], 'abstract': ' '.join(lorem_ipsum.paragraphs(3))[:1000], 'duration': '15', 'lecture_type': random.randint(0, 2), 'person_type': '2', 'description': lorem_ipsum.words(20)[:255], 'author': author } return Lecture.objects.create(**data)
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 setUpTestData(cls) -> None: cls.author = create_author() cls.author.verify() cls.topics = [create_topic(cls.author.pk) for _ in range(3)] cls.article_data = { 'title': 'Hello World', 'tags': 'hello,world', 'content': lorem_ipsum.paragraphs(4), 'topic_id': random.choice(cls.topics).id, 'thumbnail_url': 'https://picsum.photos/id/' f'{random.choice(THUMBNAIL_URL_IDs)}' '/1900/1080/', }
def create_lecture(zosia, author): data = { 'zosia': zosia, 'requests': lorem_ipsum.words(60)[:750], 'events': lorem_ipsum.words(60)[:750], 'title': lorem_ipsum.sentence()[:255], 'abstract': ' '.join(lorem_ipsum.paragraphs(3))[:1000], 'duration': random.choice(DURATION_CHOICES)[0], 'lecture_type': random.choice(LECTURE_TYPE)[0], 'person_type': LectureInternals.PERSON_NORMAL, 'description': lorem_ipsum.words(20)[:255], 'author': author } return Lecture.objects.create(**data)
def make_example_datafile(tempdir): """ Make a lorem-ipsum file in the tempdir, for demonstration purposes. """ filepath = os.path.join(tempdir, 'example_data.txt') paras = lorem_ipsum.paragraphs(3, common=True) output_text = '\n'.join(['\n'.join(textwrap.wrap(p)) for p in paras]) with open(filepath, 'w') as f: f.write(output_text) metadata = { 'tags': ['example', 'text', 'demo'], 'description': 'File with lorem ipsum text for demonstration purposes', } return filepath, metadata
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 test_paragraphs_not_common(self, mock_randint, mock_choice, mock_sample): """ paragraphs(1, common=False) generating one paragraph that's not the COMMON_P paragraph. """ # Make creating 2 sentences use 2 phrases. mock_randint.return_value = 2 mock_sample.return_value = ['exercitationem', 'perferendis'] mock_choice.return_value = '.' self.assertEqual(paragraphs(1, common=False), [ 'Exercitationem perferendis, exercitationem perferendis. ' 'Exercitationem perferendis, exercitationem perferendis.' ]) self.assertEqual(mock_randint.call_count, 7)
def test_paragraphs(self): """paragraphs(1) uses the COMMON_P paragraph.""" 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 generate(self): if self.method == 'w': lorem = lorem_ipsum.words(self.count, common=self.common) elif self.method == 's': lorem = u' '.join( [lorem_ipsum.sentence() for i in range(self.count)]) else: paras = lorem_ipsum.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(round(int(self.max_length) / 10), self.max_length) lorem = lorem[:max(1, length)] return lorem.strip()
def generate(self): if self.method == 'w': lorem = lorem_ipsum.words(self.count, common=self.common) elif self.method == 's': lorem = u' '.join([ lorem_ipsum.sentence() for i in range(self.count)]) else: paras = lorem_ipsum.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(round(int(self.max_length) / 10), self.max_length) lorem = lorem[:max(1, length)] return lorem.strip()
def test_paragraphs_not_common(self, mock_randint, mock_choice, mock_sample): """ paragraphs(1, common=False) generating one paragraph that's not the COMMON_P paragraph. """ # Make creating 2 sentences use 2 phrases. mock_randint.return_value = 2 mock_sample.return_value = ['exercitationem', 'perferendis'] mock_choice.return_value = '.' self.assertEqual( paragraphs(1, common=False), [ 'Exercitationem perferendis, exercitationem perferendis. ' 'Exercitationem perferendis, exercitationem perferendis.' ] ) self.assertEqual(mock_randint.call_count, 7)
def get_story(): """ Returns a boiler plate story as an object. """ return Story( slug="la-data-latimes-ipsum", headline="This is not a headline", byline="This is not a byline", pub_date=datetime.now(), canonical_url="http://www.example.com/", kicker="This is not a kicker", description=lorem_ipsum.COMMON_P.split(".")[0], sources="This is not a source", credits="This is not a credit", content=six.text_type("\n\n".join(lorem_ipsum.paragraphs(6))), image=get_image(900), )
def generate(self): try: from django.utils.lorem_ipsum import paragraphs, sentence, words except ImportError: # Support django < 1.8 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 random_text(paragraphs=1): return ''.join([random_char_seq(24), ' '] + lorem_ipsum.paragraphs(paragraphs))
def fuzz(self): count = random.choice(range(1, self.max_paras + 1)) return '\n\n'.join(paragraphs(count, common=False))
def get_message_view(self, request): subject = words(random.randint(5, 20), common=False) content = '\n'.join(paragraphs(random.randint(3, 6))) return self.message_view(subject, content)
def handle(self, *args, **options): count = options['count'] if count == 0: msg = 'Error - The number of markers can not be zero. Parameter: --count' raise CommandError(msg) elif count < 0: msg = 'Error - The number of markers cannot be a negative number. Parameter: --count' raise CommandError(msg) slug = 'test' ymap = Map.objects.filter(slug=slug).first() if ymap is None: msg = 'Create a map with the name - Test' raise CommandError(msg) categories = CategoryPlacemark.objects.all() count_categories = categories.count() subcategories = SubCategoryPlacemark.objects.all() count_subcategories = subcategories.count() next_number_marker = Placemark.objects.count() + 1 text = paragraphs(30, common=False)[0] icon_name_list = [ icon.slug for icon in CustomMarkerIcon.objects.filter( icon_collection=ymap.icon_collection) ] images = [ '<p><img alt="" src="/media/uploads/2019/02/13/e51b6d5e-18df-4bb0-988a-b10b7a3bebb5.jpg" style="height:214px; width:322px" /></p>', '<p><img alt="" src="/media/uploads/2019/02/13/80c1d6e5-0a8e-48e5-9fda-980666ba2525.jpg" style="height:214px; width:322px" /></p>', '<p><img alt="" src="/media/uploads/2019/02/13/f05915cb-5683-4507-a186-c7f6466408ac.jpg" style="height:214px; width:322px" /></p>', '<p><img alt="" src="/media/uploads/2019/02/13/6be19160-164d-456d-aa3e-d407d40edae5.jpg" style="height:214px; width:322px" /></p>', '<p><img alt="" src="/media/uploads/2019/02/13/e988f41a-92cd-4f6c-b8db-8655188c1f2a.jpg" style="height:214px; width:322px" /></p>', '<p><img alt="" src="/media/uploads/2019/02/13/556e0572-e8f6-4b23-96ae-b53f73587ac9.jpg" style="height:214px; width:322px" /></p>', '<p><img alt="" src="/media/uploads/2019/02/13/da2fb316-9fd9-4d96-b4dd-7e44c0610eb2.jpg" style="height:181px; width:322px" /></p>', '<p><img alt="" src="/media/uploads/2019/02/13/36fa0a2f-6784-4314-a40b-903a1a734a35.png" style="height:120px; width:120px" /></p>' ] count_images = len(images) if count_categories == 0: msg = 'Create a category for markers!' raise CommandError(msg) for num in range(count): placemark = Placemark.objects.create( ymap=ymap, category=categories[random.randrange(count_categories)], header='<p>Marker heading - {}</p>'.format(next_number_marker), body='{0}<p>{1}</p>'.format( images[random.randrange(count_images)], text[:1000]), footer='<p>Footer text information - {}</p>'.format( next_number_marker), icon_name=random.choice(icon_name_list), coordinates='[{0},{1}]'.format(random.randrange(-84, 76), random.randrange(-170, 170))) if count_subcategories > 0: placemark.subcategories.add(*[ subcategories[idx] for idx in random.sample( range(count_subcategories), random.randrange(count_subcategories) + 1) ]) next_number_marker += 1
def article(self, n): return '{0}_{1}_{2}'.format( lorem_ipsum.paragraphs(2, False), n, time.mktime(datetime.datetime.now().timetuple()))
def preview_exception(request, Ex): raise Ex( '\n\n'.join(p[:125] for p in paragraphs(2, common = False)), caption = words(4), next = lambda: reverse('home') if randint(0, 2) == 1 else None, )
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 _lorem_paras(self, count): return markdown_full(u'\n\n'.join( lorem_ipsum.paragraphs(count, common=False)) )
def create_question(): data = { 'question': lorem_ipsum.sentence()[:100], 'answer': ''.join(lorem_ipsum.paragraphs(2))[:400] } return QA.objects.create(**data)
def handle(self, *args, **options): count = options['count'] if count == 0: msg = 'Error - The number of markers can not be zero. Parameter: --count' raise CommandError(msg) elif count < 0: msg = 'Error - The number of markers cannot be a negative number. Parameter: --count' raise CommandError(msg) slug = 'test-map' media_url = getattr(settings, 'MEDIA_URL', None) ymap = Map.objects.filter(slug=slug).first() if ymap is None: msg = 'Create a map with the name - Test Map' raise CommandError(msg) elif media_url is None: msg = 'Add MEDIA_URL in settings.py' raise CommandError(msg) categories = CategoryPlacemark.objects.all() count_categories = categories.count() subcategories = SubCategoryPlacemark.objects.all() count_subcategories = subcategories.count() next_number_marker = Placemark.objects.count() + 1 text = paragraphs(30, common=False)[0] icon_name_list = [ icon.slug for icon in MarkerIcon.objects.filter( icon_collection=ymap.icon_collection) ] images = [ '<p><img alt="" src="{}uploads/2019/12/29/1.jpg" style="width:322px;" /></p>' .format(media_url), '<p><img alt="" src="{}uploads/2019/12/29/2.jpg" style="width:322px;" /></p>' .format(media_url), '<p><img alt="" src="{}uploads/2019/12/29/3.jpg" style="width:322px;" /></p>' .format(media_url), '<p><img alt="" src="{}uploads/2019/12/29/4.jpg" style="width:322px;" /></p>' .format(media_url), '<p><img alt="" src="{}uploads/2019/12/29/5.jpg" style="width:322px;" /></p>' .format(media_url), '<p><img alt="" src="{}uploads/2019/12/29/6.jpg" style="width:322px;" /></p>' .format(media_url), '<p><img alt="" src="{}uploads/2019/12/29/7.jpg" style="width:322px;" /></p>' .format(media_url), '<p><img alt="" src="{}uploads/2019/12/29/8.jpg" style="width:322px;" /></p>' .format(media_url), '<p><img alt="" src="{}uploads/2019/12/29/9.jpg" style="width:322px;" /></p>' .format(media_url), '<p><img alt="" src="{}uploads/2019/12/29/10.jpg" style="width:322px;" /></p>' .format(media_url), ] count_images = len(images) if count_categories == 0: msg = 'Create a category for markers!' raise CommandError(msg) for num in range(count): placemark = Placemark.objects.create( ymap=ymap, category=categories[random.randrange(count_categories)], header='<p>Marker Header - {}</p>'.format(next_number_marker), body='{0}<p>{1}</p>'.format( images[random.randrange(count_images)], text[:1000]), footer='<p>Footer of Marker - {}</p>'.format( next_number_marker), icon_slug=random.choice(icon_name_list), coordinates='[{0},{1}]'.format(random.randrange(-84, 76), random.randrange(-170, 170))) if count_subcategories > 0: placemark.subcategories.add(*[ subcategories[idx] for idx in random.sample( range(count_subcategories), random.randrange(count_subcategories) + 1) ]) next_number_marker += 1
def description(self): return '\n'.join(lorem_ipsum.paragraphs(3))
def create_question(): data = { 'question': lorem_ipsum.words(random.randint(5, 10)) + "?", 'answer': ''.join(lorem_ipsum.paragraphs(1))[:400], } return QA.objects.create(**data)