def createRandomDestacats(self, context, count, w, h, subject=[]): print 'creating {0} Destacats'.format(count) for i in range(count): try: title = loremipsum.get_sentence() title = re.findall('((?:\w+\s+){3})', title)[0] except: pass obj = createContentInContainer(context, u'Destacat', title=title, picture=self.getRandomImage( w, h, u'sports')) obj.text = RichTextValue(loremipsum.get_sentence()) obj.url = u'http://www.upc.edu' tag0 = choice([ 'esports colectius', 'esports d' 'adversari', 'esports individuals', 'sales d' 'activitats', 'aules d' 'aprenentatge' ]) tag1 = choice(['futbol 11', 'futbol 7', 'futbol sala', 'basquet']) obj.subject = (tag0, tag1) self.publish(obj) obj.reindexObject()
def sample_news(self): admin = User.objects.get(id=1) for i in range(20): permalink = 'example-news-%s' % i news, created = News.objects.get_or_create( permalink=permalink, defaults={ 'title': ' '.join(loremipsum.get_sentence(False).split(' ')[0:5]), 'summary': ' '.join(loremipsum.get_sentence(False).split(' ')[0:15]), 'description': loremipsum.get_paragraph(), 'permalink': permalink, 'status': STATUS_PUBLISHED, 'created_by': admin, }) if created: instance_save_image_from_url( news, 'http://lorempixel.com/430/320/nature/', rand=True) print 'Generated news: %s' % news.permalink random.shuffle(self.topic_list) for topic in self.topic_list[0:random.randrange(0, 4)]: news.topics.add(topic) self.news_list.append(news)
def createRandomNews(self, context, count): print 'creating {0} News Items'.format(count) for i in range(count): obj = createContentInContainer(context, u'News Item', title=loremipsum.get_sentence(), image=self.getRandomImage(300, 200, u'sports')) obj.text = RichTextValue(loremipsum.get_sentence()) obj.destacat = False self.publish(obj) obj.reindexObject()
def sample_relation(self, EntitySrcClass, EntityDstClass, RelationClass, is_point=False, is_data=False, is_title=False, is_description=False): entity_src_list = EntitySrcClass.objects.all() entity_dst_list = EntityDstClass.objects.all() # Loop from source sample_dst_list = [] for i in range(15): sample_dst_list.append(0) index = 0 for src in entity_src_list: for j in range(15): sample_dst_list[j] = entity_dst_list[index] if index == len(entity_dst_list) - 1: index = 0 else: index += 1 #sample_dst_list = random.sample(entity_dst_list,5) for dst in sample_dst_list: default = { 'src_id': src.id, 'dst_id': dst.id, 'status': random.choice(STATUS_CHOICES)[0] } if is_point: default['point'] = randint(0, 5) if is_data: default['data'] = 'example ' + ' '.join([ loremipsum.get_sentence(False) for ignore in range(random.randrange(1, 5)) ]) else: default['data'] = 'example' if is_title: default['title'] = 'example '.join( loremipsum.get_sentence(False).split(' ')[0:3]) if is_description: default['description'] = 'example '.join([ loremipsum.get_sentence(False) for i in range(random.randrange(1, 5)) ]) if src.id != dst.id: relation, created = RelationClass.objects.get_or_create( src_id=src.id, dst_id=dst.id, defaults=default) if created: print 'Generated: %s %s to %s' % (src.get_display_name( ), RelationClass.__name__.replace( 'Party', ''), dst.get_display_name())
def generate_project_data(): pt = Project.PROJECTTYPE data = { "submitted_event": Command.get_random_event(), "project_name": get_sentence()[:50], "short_description": get_sentence()[:300], "project_type": pt[randint(0, len(pt) - 1)][0], # pt = Project.PROJECTTYPE } return data
def test_content_visibility(self): """ Tester la publication et la visibilité des contenus """ # Créer des contenus variés content1 = Content.objects.post([self.user], 'blog', loremipsum.get_sentence()[0:100], loremipsum.get_paragraphs(8), visible=True) content2 = Content.objects.post(self.user, 'blog', loremipsum.get_sentence()[0:100], loremipsum.get_paragraphs(12), visible=False) content3 = Content.objects.post(self.user, 'blog', loremipsum.get_sentence()[0:100], loremipsum.get_paragraphs(12), visible=False) content3.publish = timezone.now() - timezone.timedelta(hours=1) content3.save() content4 = Content.objects.post(self.user, 'blog', loremipsum.get_sentence()[0:100], loremipsum.get_paragraphs(12), visible=False) content4.publish = timezone.now() + timezone.timedelta(hours=1) content4.save() content5 = Content.objects.post(self.administrator, 'blog', loremipsum.get_sentence()[0:100], loremipsum.get_paragraphs(12), visible=True) self.assertFalse(content1.is_published(), "content 1 should be unpublished" ) # Approval sets published to False for base users self.assertFalse(content2.is_published(), "content 2 should be unpublished") self.assertFalse(content3.is_published(), "content 3 should be unpublished") self.assertFalse(content4.is_published(), "content 4 should be unpublished") self.assertFalse(content5.is_published(), "content 5 should be unpublished") self.assertEqual(Content.objects.visible().count(), 0, "there should be exactly 1 visible content") # Approuver un contenu content1.approval.approve(save=True) self.assertTrue(content1.is_published(), "content 1 should be now published") # Tester le statut du contenu self.assertGreater( len(content1.html), 10, "the html display for the content should not be populated")
def generate_note_data(max_length=300): content = get_paragraph()[:max_length] # add random hashtags content += '\n' + get_sentence().replace(' ', ' #') data = { 'title': get_sentence(), 'content': content, 'color': Command.random_color(), 'is_pinned': bool(randint(0, 1)), 'is_archived': bool(randint(0, 1)), } return data
def createRandomNews(self, context, count): print 'creating {0} News Items'.format(count) for i in range(count): obj = createContentInContainer(context, u'News Item', title=loremipsum.get_sentence(), image=self.getRandomImage( 300, 200, u'sports')) obj.text = RichTextValue(loremipsum.get_sentence()) obj.destacat = False self.publish(obj) obj.reindexObject()
def setUp(self): """ Définir l'environnement de test """ self.engine = import_module(settings.SESSION_ENGINE) self.session = self.engine.SessionStore() self.user = User.objects.create(username='******', email='*****@*****.**') self.user.set_password('commentuser') self.user.save() # Créer des contenus commentables ou pas self.content1 = Content.objects.post([self.user], 'blog', loremipsum.get_sentence()[0:100], loremipsum.get_paragraphs(8), visible=True, commentable=True) self.content2 = Content.objects.post([self.user], 'blog', loremipsum.get_sentence()[0:100], loremipsum.get_paragraphs(8), visible=True, commentable=False) # Commenter l'utilisateur et tester l'état des commentaires self.comment1 = Comment.objects.comment(None, self.user, self.user, "Commentaire 1", force=True) self.comment2 = Comment.objects.comment(None, self.user, self.user, "Commentaire 2", force=True) self.comment3 = Comment.objects.comment(None, self.user, self.user, "Commentaire 3", force=True) self.comment4 = Comment.objects.comment(None, self.user, self.user, "Commentaire 4", force=True) self.comment5 = Comment.objects.comment( None, self.user, self.user, "Commentaire 5" ) # échec : user n'est pas un commentablemodel et force == False self.comment6 = Comment.objects.comment(None, self.user, self.content1, "Commentaire 6") self.comment7 = Comment.objects.comment( None, self.user, self.content2, "Commentaire 7") # échec : content.commentable == False
def __auto_populate(num_of_stories=10, num_of_tags=10): # generate tags for i in xrange(num_of_tags): t = Tag(name=LI.get_sentence().split()[0]) t.save() tags = Tag.objects.all() for i in xrange(num_of_stories): s = Story(title=LI.get_sentence(), body=LI.get_paragraph()) s.save() for j in xrange(rnd.randint(1, 4)): tag_idx = rnd.randint(0, len(tags)-1) s.tag.add(tags[tag_idx]) s.save()
def generate_demographic_poll(owner): question = DemographicQuestion() question.question = loremipsum.get_sentence() question.created_by = owner question.modified_by = owner question.save() for respondent in Respondent.objects.all(): answer = DemographicQuestionResponse() answer.question = question answer.respondent = respondent answer.response = loremipsum.get_sentence() answer.save()
def sample_event(self): admin = User.objects.get(id=1) for i in range(20): permalink = 'example-event-%s' % i event, created = Event.objects.get_or_create( permalink=permalink, defaults={ 'title': ' '.join(loremipsum.get_sentence(False).split(' ')[0:5]), 'summary': ' '.join(loremipsum.get_sentence(False).split(' ')[0:15]), 'description': loremipsum.get_paragraph(), 'permalink': permalink, 'status': STATUS_PUBLISHED, 'created_by': admin, 'start_date': timezone.now(), 'end_date': timezone.now(), 'phone': '08123456789', 'email': '*****@*****.**', 'facebook_url': 'http://facebook.com/%s' % permalink, 'twitter_url': 'http://twitter.com/%s' % permalink, 'homepage_url': 'http://homepage.com/%s' % permalink, 'location': ' '.join(loremipsum.get_sentence(False).split(' ')[0:20]), }) if created: instance_save_image_from_url( event, 'http://lorempixel.com/430/320/nature/', rand=True) print 'Generated event: %s' % event.permalink random.shuffle(self.topic_list) for topic in self.topic_list[0:random.randrange(0, 4)]: event.topics.add(topic) self.event_list.append(event)
def createRandomDestacats(self, context, count, w, h, subject=[]): print 'creating {0} Destacats'.format(count) for i in range(count): try: title = loremipsum.get_sentence() title = re.findall('((?:\w+\s+){3})', title)[0] except: pass obj = createContentInContainer(context, u'Destacat', title=title, picture=self.getRandomImage(w, h, u'sports')) obj.text = RichTextValue(loremipsum.get_sentence()) obj.url = u'http://www.upc.edu' tag0 = choice(['esports colectius', 'esports d''adversari', 'esports individuals', 'sales d''activitats', 'aules d''aprenentatge']) tag1 = choice(['futbol 11', 'futbol 7', 'futbol sala', 'basquet']) obj.subject = (tag0, tag1) self.publish(obj) obj.reindexObject()
def post(self): # log in self._login() # post a chirp from a lorem ipsum sentence self.client.post(settings.BASE_URL+'/'+self.user.username, {'form.submitted': True, 'chirp': get_sentence()}, name="/{username}[post]")
def get(self, request): item = models.Posts() item.created_at = datetime.now() item.posted_by = models.Users.objects.order_by('?').first() item.status = 'Publish' item.title = get_sentence(1) item.context = get_sentence(5) item.disallow_comments = False item.updated_on = datetime.now() item.save() return JsonResponse({ 'id': item.id, 'posted_by': item.posted_by.username, 'title': item.title, 'context': item.context })
def get_random_data(users, min_boards, max_boards, min_tickets, max_tickets): data = [] for i in range(users): user_name = DEFAULT_USER.format(str(i)) password = DEFAULT_PASSWD.format(str(i)) user = {'email': user_name, 'password': password, 'boards': []} for _ in range(random.randint(min_boards, max_boards)): lorem = loremipsum.get_sentence() board = {'name': lorem, 'tickets': []} for _ in range(random.randint(min_tickets, max_tickets)): lorem = loremipsum.get_sentence() ticket = {'content': lorem} board['tickets'].append(ticket) user['boards'].append(board) data.append(user) return data
def gen_text(): def alter(w): if gen_bool(0.9): return w return random.choice(['`{}`', '_{}_', '*{}*']).format(w) return ' '.join(alter(w) for w in loremipsum.get_sentence().split())
def create_library_content(parent, spec, force=False, creator='alice_lindstrom', bigsetup=False): if parent is None: # initial recursion portal = api.portal.get() parent = portal.library api.user.grant_roles(username=creator, roles=['Contributor', 'Reviewer', 'Editor'], obj=portal.library) try: api.content.transition(portal.library, 'publish') except api.exc.InvalidParameterError: # subsequent runs, already published pass # initial (automated testing) testcontent run: no children # second manual testcontent run: 1 child HR -> do big setup # subsequent manual testcontent runs: skip for speed already_setup = bool(len(portal.library.objectIds()) > 1) if already_setup and not force: log.info("library already setup. skipping for speed.") return # recursively called while spec: # avoiding side effects here cost me 4 hours!! item = copy.deepcopy(spec.pop(0)) if 'title' not in item and not bigsetup: # skip lorem ipsum creation unless we're running bigsetup continue contents = item.pop('contents', None) if 'title' not in item: global idcounter idcounter += 1 item['title'] = 'Lorem Ipsum %s' % idcounter if 'description' not in item: item['description'] = loremipsum.get_sentence() if item['type'] in ('Document', ): raw_text = "\n\n".join(loremipsum.get_paragraphs(3)) item['text'] = RichTextValue(raw=raw_text, mimeType='text/plain', outputMimeType='text/x-html-safe') obj = create_as(creator, container=parent, **item) if not item['type'].startswith('ploneintranet'): # only tag non-folderish content tags = random.sample(library_tags, random.choice(range(4))) tags.append(u'I ♥ UTF-8') wrapped = IDublinCore(obj) wrapped.subjects = tags api.content.transition(obj, 'publish') obj.reindexObject() # or solr doesn't find it if contents: create_library_content(obj, contents, creator=creator, bigsetup=bigsetup)
def fuzz(self): ret = "" for outer in range(random.randint(1, 5)): ret += "\n\n" for inner in range(random.randint(3, 10)): ret += self.fixer.sub(self.fixto, loremipsum.get_sentence()).capitalize() + " " return ret.strip()
def setUp(self): # ?Change only var values below # Amount of supliers you wanna create suplier_amount = 5 # Amount of bonuses you wanna create bonus_amount = 20 # Suplier creating block for suplier in range(suplier_amount): models.Suplier.objects.create( title=f'TESTING CASINO {suplier}', ca_license_bool=choice([True, False]), suplier_type=randint(0, 3), ) # Bonus creating block for bonus in range(bonus_amount): models.Bonus.objects.create( two_word_desc=f'TESTING BONUS {bonus}', bonus_digit=randrange(5000), bonus_desc=get_sentence(5), suplier=models.Suplier.objects.get( pk=randint(1, suplier_amount)), dep_bool=choice([True, False]), dep=randint(1, 10000), doe=timezone.now() + datetime.timedelta(days=randint(1, 200)), wager=randint(1, 50), bonus_type=choice((0, 1)), )
def create_library_content(parent, spec, force=False, creator='alice_lindstrom', bigsetup=False): if parent is None: # initial recursion portal = api.portal.get() parent = portal.library api.user.grant_roles( username=creator, roles=['Contributor', 'Reviewer', 'Editor'], obj=portal.library ) try: api.content.transition(portal.library, 'publish') except api.exc.InvalidParameterError: # subsequent runs, already published pass # initial (automated testing) testcontent run: no children # second manual testcontent run: 1 child HR -> do big setup # subsequent manual testcontent runs: skip for speed already_setup = bool(len(portal.library.objectIds()) > 1) if already_setup and not force: log.info("library already setup. skipping for speed.") return # recursively called while spec: # avoiding side effects here cost me 4 hours!! item = copy.deepcopy(spec.pop(0)) if 'title' not in item and not bigsetup: # skip lorem ipsum creation unless we're running bigsetup continue contents = item.pop('contents', None) if 'title' not in item: global idcounter idcounter += 1 item['title'] = 'Lorem Ipsum %s' % idcounter if 'description' not in item: item['description'] = loremipsum.get_sentence() if item['type'] in ('Document',): raw_text = "\n\n".join(loremipsum.get_paragraphs(3)) item['text'] = RichTextValue(raw=raw_text, mimeType='text/plain', outputMimeType='text/x-html-safe') obj = create_as(creator, container=parent, **item) if not item['type'].startswith('ploneintranet'): # only tag non-folderish content tags = random.sample(library_tags, random.choice(range(4))) tags.append(u'I ♥ UTF-8') wrapped = IDublinCore(obj) wrapped.subjects = tags api.content.transition(obj, 'publish') obj.reindexObject() # or solr doesn't find it if contents: create_library_content(obj, contents, creator=creator, bigsetup=bigsetup)
def get(self, number=10, bulk=False, **kwargs): """randomly generated document, title and text based on loremipsum module, image is a link to lorempixel random image Parameters ---- number : int The number of test documents to generated bulk : bool (default=False) Whether to yield single documents (if False) or a list of documents (if True) """ start = randint(0, 1000) batch = [] for i in range(number): fake_id = i + start doc = { "_id": "testdoc_{fake_id}".format(**locals()), "title": prettier(loremipsum.get_sentence()), "text": prettier(loremipsum.get_paragraph()), "image": "http://lorempixel.com/400/200/", } doc.update(kwargs) if not bulk: yield doc else: batch.append(doc) if not len(batch) % (number / 10): yield batch batch = [] if bulk and batch: yield batch
def test_batch_header(self): self.ach_file.new_batch(randint(111111111, 999999999), get_sentence()) test_batch = self.ach_file.batch_records[-1].generate() self.assertEqual(len(test_batch), 95) self.assertEqual(test_batch[:1], '5') self.assertEqual(test_batch[75:78], ' ') self.assertEqual(test_batch[78:79], '1')
def createRandomEvents(self, context, count): print 'creating {0} Events'.format(count) for i in range(count): obj = createContentInContainer(context, u'Event', title=loremipsum.get_sentence()) obj.description = loremipsum.get_paragraph() self.publish(obj) obj.reindexObject()
def sample_people(self): # Generate 60 users with lorempixel for i in range(0, 60): user_role = random.choice(self.user_role_list) user, created = User.objects.get_or_create( email='*****@*****.**' % i, defaults={ 'email': '*****@*****.**' % i, 'priority': randint(0, 10), 'username': '******' % i, 'first_name': names.get_first_name(), 'last_name': names.get_last_name(), 'occupation': ' '.join(loremipsum.get_sentence(False).split(' ')[0:3]), 'summary': ' '.join(loremipsum.get_sentence(False).split(' ')[0:15]), 'description': loremipsum.get_paragraph(), 'facebook_url': 'https://www.facebook.com/username%s' % i, 'twitter_url': 'https://www.twitter.com/username%s' % i, 'linkedin_url': 'https://www.linkedin.com/username%s' % i, 'homepage_url': 'https://www.homepage.com/username%s' % i, }) if created: user.set_password('password') user.country = random.choice(self.country_list) user.user_roles.add(user_role) user.save() instance_save_image_from_url( user, 'http://lorempixel.com/430/320/people/', rand=True) print 'Generated user : %s (%s)' % (user.get_display_name(), user.email) self.user_list.append(user)
def generate_random_data(): from models import Area, User, Ticket, Note, TicketCloseReason import random import loremipsum db.drop_all() db.create_all() areas = [ Area(name=u'CTO'), Area(name=u'Network'), Area(name=u'Infrastructure'), Area(name=u'Devops'), Area(name=u'Helpdesk'), ] db.session.add_all(areas) db.session.commit() users = [ User(user='******', name=u'Bruno Bonagura', areas=areas, access_admin=True, access_reports=False), ] users[0].set_password('ax886dds') db.session.add_all(users) reasons = [ TicketCloseReason(reason=u'Solved'), TicketCloseReason(reason=u'False Alarm'), TicketCloseReason(reason=u'Network failure'), TicketCloseReason(reason=u'Misconfiguration'), TicketCloseReason(reason=u'Remission') ] db.session.add_all(reasons) db.session.commit() random.seed('oi') for i in range(1, 100): t = Ticket( title = unicode(loremipsum.get_sentence()), text = unicode(loremipsum.get_paragraph()), current_area = random.choice(areas), created_at = datetime.now() - timedelta(random.randint(1,100)), created_by = random.choice(users), ) t.add_note(random.choice(users), unicode(loremipsum.get_sentence())) db.session.add(t) db.session.commit()
def createRandomBanners(self, context, count, w, h): print 'creating {0} Banners'.format(count) for i in range(count): obj = createContentInContainer(context, u'BannerEsports', title=loremipsum.get_sentence(), picture=self.getRandomImage(w, h, u'sports')) obj.description = loremipsum.get_paragraph() obj.url = u'http://www.upc.edu' self.publish(obj) obj.reindexObject()
def setUp(self): self.data = loremipsum.get_sentence() self.dir_path = self._testMethodName + "_dir" self.vol.mkdir(self.dir_path, 0755) self.file_path = self.dir_path + "/" + self.testfile with self.vol.creat( self.file_path, os.O_WRONLY | os.O_EXCL, 0644) as fd: rc = fd.write(self.data) self.assertEqual(rc, len(self.data))
def get_random_event(): if Event.objects.exists(): event = Event.objects.order_by("?")[:1].first() else: # make a random event event_name = get_sentence()[:50] address = get_sentence()[:100] event_data = { "event_name": event_name, "slug": event_name.replace(" ", "-"), "start_date": timezone.now(), "end_date": timezone.now(), "address": address, "city": address.split()[-1], "location": Geoposition(randint(-90, 90), randint(-90, 90)), } event = Event.objects.create(**event_data) return event
def __init__(self): self.date = datetime.datetime.now().replace(microsecond=0, tzinfo=pytz.utc) self.text = get_sentence(True) self.app = 'DummyAppName' self.dyno = 'web.1' self.msg = '<40>1 {} host {} {} - {}\n'.format(self.date.isoformat(), self.app, self.dyno, self.text)
def gen_text(max_chars): text = '' target_chars = int(max_chars * random.random()) while len(text) < target_chars: left = max_chars - len(text) if left < 20 and text != '': break candidate = loremipsum.get_sentence() if len(candidate) < left: text += candidate return text
def test_content_properties(self): """ Tester la publication et la visibilité des contenus """ content1 = Content.objects.post([self.user], 'blog', loremipsum.get_sentence()[0:100], loremipsum.get_paragraphs(8), visible=True) self.assertTrue(content1.is_new(), "this new content should be considered new")
def test_entry_record_without_addenda(self): self.ach_file.batch_records[-1].add_entry(ACHRecordTypes.CHECK_DEPOSIT, randint(111111111, 999999999), randint(111111111, 999999999), randint(111111111, 999999999), randint(111111111, 999999999), get_sentence()) test_entry_record = self.ach_file.batch_records[-1].entry_records[-1] test_entry = test_entry_record.generate() self.assertEqual(len(test_entry), 95) self.assertEqual(test_entry[:1], '6')
def test_post_requirement3(self, setup): """ Test POST /quotes of 25 new entries. Requirement: Storing at least 20 quotes is supported. """ num_new_entries = 25 # Get the initial id entries from the server initial_ids = _get_ids_from_server(setup.session, setup.send_request) num_initial_ids = len(initial_ids) logger.debug(f'num_initial_ids: {num_initial_ids}') # Loop to create the number of new entries for x in range(num_new_entries): logger.debug(f'x: {x}') quote_text = get_sentence(True) post_response = setup.send_request.post( setup.session, '{"text": "' + quote_text + '"}') assert_status(post_response, 201) post_response_status_code = _get_status_code(post_response) post_response_ok = _get_key_value_from_response( post_response, 'ok') post_response_data = _get_key_value_from_response( post_response, 'data') new_id = _get_first_value_for_key_from_response_data( post_response_data, 'id') logger.debug(f'new_id: {new_id}') response_text = _get_first_value_for_key_from_response_data( post_response_data, 'text') logger.debug(f'response_text: {response_text}') try: cur_get_response = setup.send_request.get(setup.session) assert_status(cur_get_response, 200) cur_get_response_data = _get_key_value_from_response( cur_get_response, 'data') cur_ids = _get_all_values_for_key_from_response_data( cur_get_response_data, 'id') assert post_response_status_code == 201 assert post_response_ok is True assert response_text == quote_text assert new_id not in initial_ids assert new_id in cur_ids except (AssertionError, TypeError): num_current_entries = num_initial_ids + x logger.error( f'Invalid response from server when number of quotes exceeds {num_current_entries}' ) # Get the final id entries from the server final_ids = _get_ids_from_server(setup.session, setup.send_request) num_final_ids = sum(1 for _ in final_ids) logger.debug(f'num_final_ids: {num_final_ids}') assert num_final_ids == num_initial_ids + num_new_entries
def createRandomEvent(request): Event.objects.create( reporter_first=names.get_first_name(), reporter_last=names.get_last_name(), phone_number=gen_random_number(), postal_code=valid_postal(), add_desc=lorem.get_sentence(True), assist_type=gen_assist_type() ) return render(request, 'gen.html')
def setUp(self): self.data = loremipsum.get_sentence() self.path = self._testMethodName + ".io" with self.vol.open(self.path, os.O_CREAT | os.O_WRONLY | os.O_EXCL, 0644) as fd: rc = fd.write(self.data) self.assertEqual(rc, len(self.data)) ret = fd.fsync() self.assertEqual(ret, 0) self.assertEqual(fd.originalpath, self.path)
def test_entry_record_with_addenda(self): self.ach_file.batch_records[-1].add_entry(ACHRecordTypes.CHECK_DEPOSIT, randint(111111111, 999999999), randint(111111111, 999999999), randint(111111111, 999999999), get_sentence(), get_sentence()) entry_record = self.ach_file.batch_records[-1].entry_records[-1] entry_record.add_addenda('test', ACHRecordTypes.CCD) addenda_record = entry_record.addenda_records[-1] test_addenda = addenda_record.generate() self.assertEqual(len(test_addenda), 95) self.assertEqual(test_addenda[:1], '7')
def create_simple_document(i): title = loremipsum.get_sentence().replace('.', '') category = categories[(i / 14)].title() return { 'id': i, 'title': title, 'category': category, 'thumbnailImg': 'http://lorempixel.com/100/100/{}'.format(category.lower()) }
def run_client(num_messages): sock = socket.socket() sock.connect(('localhost',8080)) for i in range(num_messages): wait_time = random.randint(0,10) time.sleep(wait_time) sock.send('{}\n'.format(loremipsum.get_sentence())) sock.close()
def run_client(num_messages): sock = socket.socket() sock.connect(('localhost', 8080)) for i in range(num_messages): wait_time = random.randint(0, 10) time.sleep(wait_time) sock.send('{}\n'.format(loremipsum.get_sentence())) sock.close()
def log_generator(): for i in xrange(size): random_td = timedelta(microseconds=60 * 60 * 1000 - random.randint(i * 1000, (i + 1) * 1000)) yield { '_id': str(random.randint(0, 10000000)), '_source': { '@timestamp': (datetime.now() - random_td).isoformat(), 'file': '/var/log/{0}'.format(get_logfile_name()), 'loglevel': random.choice(LOGLEVELS), 'log_message': get_sentence(), }}
def setUp(self): self.data = loremipsum.get_sentence() self.dir_path = self._testMethodName + "_dir" self.vol.mkdir(self.dir_path, 0755) for x in range(0, 3): f = os.path.join(self.dir_path, self.testfile + str(x)) with self.vol.open(f, os.O_CREAT | os.O_WRONLY | os.O_EXCL, 0644) as fd: rc = fd.write(self.data) self.assertEqual(rc, len(self.data)) ret = fd.fdatasync() self.assertEqual(ret, 0)
def createRandomBanners(self, context, count, w, h): print 'creating {0} Banners'.format(count) for i in range(count): obj = createContentInContainer(context, u'BannerEsports', title=loremipsum.get_sentence(), picture=self.getRandomImage( w, h, u'sports')) obj.description = loremipsum.get_paragraph() obj.url = u'http://www.upc.edu' self.publish(obj) obj.reindexObject()
def to_defaults(soup, fields={}, prefix=True): """ Parses the source soup and generates lorem ipsum for values that are blank :param soup: BeautifulSoup :param fields: initial data :return: soup, fields """ soup, fields = Template.to_fields(soup, prefix) for k, v in fields.items(): if len(v) == 0: fields[k] = get_sentence() return soup, fields
def test_content_authors(self): """ Tester la publication et la visibilité des contenus """ content1 = Content.objects.post([self.user], 'blog', loremipsum.get_sentence()[0:100], loremipsum.get_paragraphs(8), visible=True) content5 = Content.objects.post(self.administrator, 'blog', loremipsum.get_sentence()[0:100], loremipsum.get_paragraphs(12), visible=True) self.assertTrue(content1.is_author(self.user), "cannot find expected author in content1") self.assertTrue(content5.is_author(self.administrator), "cannot find expected author in content5") self.assertFalse(content5.is_author(self.user), "found unexpected author in content5") self.assertTrue(content1.is_editable(self.user), "content1 should be editable by user") self.assertTrue(content1.is_editable(self.administrator), "content5 should be editable by admin")
def setUp(self): mock_casnio = models.Suplier.objects.create(title='TESTING CASINO') mock_bonus = models.Bonus.objects.create( two_word_desc='TESTING BONUS', bonus_digit=1000, bonus_desc=get_sentence(5), suplier=mock_casnio, dep_bool=True, dep=5000, doe=timezone.now() + datetime.timedelta(days=30), wager=20, bonus_type=0, )
def test_content_categories(self): """ Tester la publication et la visibilité des contenus """ content1 = Content.objects.post([self.user], 'blog', loremipsum.get_sentence()[0:100], loremipsum.get_paragraphs(8), visible=True) self.assertIsNotNone(Category.objects.get_by_url('blog'), "a content type with the blog path should exist") self.assertGreater( Category.objects.all().count(), 0, "could not find any content type, which should be impossible") self.assertEqual(content1.category.short_name, 'blog', "content 1 should be a 'blog' entry")
def gen_score(backup, admin, kind="autograder"): created = datetime.datetime.now() - datetime.timedelta( minutes=random.randrange(100)) if kind == "composition": score = random.randrange(2) else: score = random.uniform(0, 100) return Score(created=created, backup_id=backup.id, assignment_id=backup.assignment.id, grader_id=admin.id, kind=kind, score=score, message=loremipsum.get_sentence())
def generate_lorem_sentence(): """ Generate a sentence of lorem ipsum. The loremipsum library is broken and returns things like "B'lorem' b'ipsum' b'next' b'nextword'." This just trims off the byte string markers that we're getting. """ result = [] lorem_sentence = loremipsum.get_sentence().split() for word in lorem_sentence: if word[-1] != "'": end_trim_index = len(word) - 2 else: end_trim_index = len(word) - 1 result.append(word[2:end_trim_index]) return " ".join(result) + '.'
def gen_score(backup, admin, kind="autograder"): created = datetime.datetime.now() - datetime.timedelta(minutes=random.randrange(100)) if kind == "composition": score = random.randrange(2) else: score = random.uniform(0, 100) return Score( created=created, backup_id=backup.id, assignment_id=backup.assignment.id, grader_id=admin.id, kind=kind, score=score, message=loremipsum.get_sentence())
def create_sample_user(self, count): firstname = names.get_first_name() lastname = names.get_last_name() username = firstname[0].lower() + lastname.lower() email = username + '@dir.app' password = username address = get_sentence()[0:50] phone = '+' + str(randint(100,999)) + '-' + str(randint(100000000,999999999)) user = User.objects.create_user(username=username, email=email, password=password) user.first_name = firstname user.last_name = lastname user.save() profile = UserProfile.objects.create(user=user, Address=address, Phone=phone,) profile.save() print "Creating user %i" % count
def generate(line_length, total_length): lines = [] current_length = 0 while True: current_line_length = 0 line = [] while True: s = loremipsum.get_sentence() line.append(s) current_line_length += len(s) if current_line_length > line_length: break lines.append(' '.join(line) + '\n') current_length += len(lines[-1]) if current_length > total_length: break return ''.join(lines)
def post_chirp(self): latency=0 timer = () br = self.br _ = br.open(BASE_URL+'/'+self.username) # chirps_count=random.randrange(1, MAX_CHIRPS) # for i in range(chirps_count): br.select_form(nr=0) br.form[ 'chirp' ] = get_sentence() start_timer = time.time() resp = br.submit() resp.read() latency += time.time() - start_timer # verify responses are valid assert (resp.code == 200), 'Bad Response: HTTP %s' % resp.code # assert ('my birdie' in resp.get_data()), 'Text Assertion Failed' timer = 'Chirp', latency return timer
def get_tweet(self): return loremipsum.get_sentence()
def test_get_sentence(self): """Test loremipsum.get_sentence function.""" self.assertIsInstance(loremipsum.get_sentence(), self._unicode_str)
def remove_things(things): for thing in things: # Seems to be in users's timezone. Unclear. thing_time = datetime.fromtimestamp(thing.created_utc) # Exclude items from being deleted unless past X hours. after_time = datetime.now() - timedelta(hours=hours) if thing_time > after_time: if thing_time + timedelta(hours=nuke_hours) < datetime.utcnow(): pass continue # For edit_only we're assuming that the hours aren't altered. # This saves time when deleting (you don't edit already edited posts). if edit_only: end_time = after_time - timedelta(hours=hours) if thing_time < end_time: continue if str(thing.subreddit).lower() in whitelist or \ thing.id in whitelist_ids: continue if whitelist_distinguished and thing.distinguished: continue if whitelist_gilded and thing.gilded: continue if max_score is not None and thing.score > max_score: continue if trial_run: # Don't do anything, trial mode! log.debug("Would have deleted {thing}: '{content}'".format( thing=thing.id, content=thing)) continue if save_directory: if not os.path.exists(save_directory): os.makedirs(save_directory) with open("%s/%s.json" % (save_directory, thing.id), "w") as fh: json.dump(thing.json_dict, fh) if clear_vote: thing.clear_vote() if isinstance(thing, Submission): log.info('Deleting submission: #{id} {url}'.format( id=thing.id, url=thing.url.encode('utf-8')) ) elif isinstance(thing, Comment): replacement_text = get_sentence() msg = '/r/{3}/ #{0} with:\n\t"{1}" to\n\t"{2}"'.format( thing.id, sub(b'\n\r\t', ' ', thing.body[:78].encode('utf-8')), replacement_text[:78], thing.subreddit ) if edit_only: log.info('Editing (not removing) {msg}'.format(msg=msg)) else: log.info('Editing and deleting {msg}'.format(msg=msg)) thing.edit(replacement_text) if not edit_only: thing.delete()