Пример #1
0
    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")
Пример #2
0
    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
Пример #3
0
def createSituationReport(self):
    """
    """
    prefix = self.prefix or self.getId()
    gname = "%s_Group%d" % (prefix, 2)
    g = None
    try:
        g = self.content.Groups[gname]
    except:
        return
    createPloneObjects(g, [ {TYPE: 'SRFolder', TITLE: 'Lagebericht', ID: 'lagebericht', CHILDREN: [] } ])
    path = g.lagebericht
    intids = getUtility(IIntIds)

    for mt in ModuleTypesVocabularyFactory(self, raw=True):
        
        docid = mt[0]
        # Generate random text for description
        
        d = chomsky(2)
        t = "<p>" + "</p><p>".join(get_paragraphs(3)) + "</p>"

        if not hasattr(path, docid):        
            path.invokeFactory(id=docid, type_name="SRModule", title=mt[1], description="")
            d = path._getOb(docid)
            d.text = RichTextValue(safe_unicode(t))
            d.docType = mt[0]
            d.doc_extension(ELAN_APP).scenarios = ["scenario1", "scenario2"]
            d.reindexObject()
            d.publishModule(justDoIt=True)
    
    transaction.commit()
    if not hasattr(path, "lage"):        
        path.invokeFactory(id="lage", type_name="SituationReport", title="Aktueller Lagebericht", description="")
        d = path._getOb("lage")
        t = "<p>" + "</p><p>".join(get_paragraphs(3)) + "</p>"
        d.text = RichTextValue(safe_unicode(t))
        phase = self.contentconfig.srconfig.scenario1.phase1
        to_id = intids.getId(phase)
        d.phase = RelationValue(to_id)
        mods = [ m.getObject() for m in queryForObjects(self, path = "/".join(path.getPhysicalPath()), portal_type='SRModule', review_state='published', sort_on='getId') ] 
        refs = []
        for mod in mods:
            #print idx
            to_id = intids.getId(mod)
            refs.append(RelationValue(to_id))
        d.currentModules=refs
        d.doc_extension(ELAN_APP).scenarios = ["scenario1", "scenario2"]
        d.reindexObject()
        d.publishReport(justDoIt=True, duplicate=True)
Пример #4
0
def main():
    length = random.randint(16, 32)
    paragraphs = loremipsum.get_paragraphs(length, True)
    text = '\n\n'.join(paragraphs)
    process = Popen(['stegsnow', '-C', '-f', 'flag.txt'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
    stdout, stderr = process.communicate(text)
    print(stdout.strip())
def synthetic_student_data(student_id):
    '''
    Create fake student data for mock-up UX for one student
    '''
    name = names.get_first_name()
    essay = "\n".join(loremipsum.get_paragraphs(5))
    return {
        'id': student_id,
        'name': name,
        'email': "{name}@school.district.us".format(name=name),
        'address': "1 Main St",
        'phone': "({pre})-{mid}-{post}".format(
            pre=random.randint(200, 999),
            mid=random.randint(200, 999),
            post=random.randint(1000, 9999)),
        'avatar': "avatar-{number}".format(number=random.randint(0, 14)),
        'ici': random.uniform(100, 1000),
        'essay_length': len(essay),
        'essay': essay,
        'writing_time': random.uniform(5, 60),
        'text_complexity': random.uniform(3, 9),
        'google_doc': "https://docs.google.com/document/d/1YbtJGn7ida2IYNgwCFk3SjhsZ0ztpG5bMzA3WNbVNhU/edit",
        'time_idle': numpy.random.gamma(0.5, scale=5),
        'outline': [{"section": "Problem " + str(i + 1),
                     "length": random.randint(1, 300)} for i in range(5)],
        'revisions': {}
    }
Пример #6
0
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)
Пример #7
0
 def generateMessage(self, **kwargs):
     """This method generates a lorem ipsum message of a specified size"""
     numParagraphs = kwargs['paragraph']
     if (numParagraphs < 1):
         print 'Warning! Number of paragraphs must be over than 0. Defaulting to 1...'
         numParagraphs = 1
     self.message = loremipsum.get_paragraphs(numParagraphs)
Пример #8
0
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)
Пример #9
0
 def submit_response(self):
     """
     Submit a response.
     """
     payload = json.dumps({
         'submission': u' '.join(loremipsum.get_paragraphs(random.randint(1, 10))),
     })
     self.client.post(self.handler_url('submit'), data=payload, headers=self._post_headers, verify=False)
Пример #10
0
def revision(repository, author):
    result = Revision(
        repository=repository, sha=uuid4().hex, author=author,
        message='\n\n'.join(get_paragraphs(2)),
    )
    db.session.add(result)

    return result
 def test_description_is_very_long(self):
     paragraphs = get_paragraphs(25)
     lorem_ipsum = ', '.join(paragraphs)
     election = Election.objects.create(
         name='the name',
         description=lorem_ipsum
         )
     self.assertEquals(election.description, lorem_ipsum)
Пример #12
0
 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")
Пример #13
0
def add_comment():
    films = Film.objects.all()
    users = CustomUser.objects.all()
    for f in films:
        for r in range(0, random.randint(1, 3)):
            comm = Comment()
            comm.film = f
            comm.user = random.choice(users)
            comm.text = get_paragraphs(random.randint(1, 4))
            comm.save()
Пример #14
0
 def get(self, count, response_format=None):
     count = min(count, 100)
     items = get_paragraphs(count)
     if response_format.lower() == 'html':
         return output_html(items, 200)
     elif response_format.lower() == 'html_code':
         return output_html_code(items, 200)
     elif response_format.lower() == 'text':
         return output_text(items, 200)
     return {'paragraphs': items}
Пример #15
0
 def handle(self, *args, **options):
     #Post.objects.all().delete()
     for a in range(1000):
         text = ""
         for elem in get_paragraphs(random.randrange(1,20)):
             text = "%s <p>%s</p>"%(text,elem)
         title = "Test Post %s"%(a)
         timestamp = datetime.datetime(year = random.randrange(2007,2016), month = random.randrange(1,13), day = random.randrange(1,29))
         post = Post.objects.create(title=title,content=text,timestamp=timestamp)
         #self.stdout.write(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))
Пример #16
0
def revision(repository, author):
    result = Revision(
        repository=repository, sha=uuid4().hex, author=author,
        repository_id=repository.id, author_id=author.id,
        message='\n\n'.join(get_paragraphs(2)),
        branches=['default', 'foobar'],
    )
    db.session.add(result)

    return result
Пример #17
0
 def peer_assess(self):
     """
     Assess a peer.
     """
     payload = json.dumps({
         'submission_uuid': self._submission_uuid('peer'),
         'options_selected': self.OPTIONS_SELECTED,
         'feedback': loremipsum.get_paragraphs(random.randint(1, 3)),
     })
     self.client.post(self.handler_url('peer_assess'), data=payload, headers=self._post_headers, verify=False)
    def handle(self, *args, **kwargs):
        provider = User.objects.get(pk=1)
        for i in range(0, kwargs['amount']):
            location = CITIES[random.randint(0, len(CITIES) - 1)]
            experience = Experience.objects.create(
                user=provider,
                title=' '.join(
                    get_sentence().split()[:random.randint(2, 5)]).title(),
                description='\n\n'.join(get_paragraphs(random.randint(1, 3))),
                location=location[0],
                coords=Point(location[1], location[2]),
                terms='\n'.join(get_paragraphs(random.randint(1, 2))),
                pax_adults=random.randint(1, 4),
                pax_children=random.randint(0, 3),
            )

            for inc in get_sentences(random.randint(1, 4)):
                ExperienceInclusion.objects.create(
                    experience=experience,
                    name=' '.join(inc.split()[:random.randint(2, 4)]).title())

            for exc in get_sentences(random.randint(1, 4)):
                ExperienceExclusion.objects.create(
                    experience=experience,
                    name=' '.join(exc.split()[:random.randint(2, 4)]).title())

            images = self._get_images()
            num_images = random.randint(2, 6)
            for i in range(0, num_images):
                image = images.pop(random.randint(0, len(images) - 1))
                with open(image, 'rb') as fh:
                    path = os.path.join(settings.MEDIA_ROOT,
                                        ExperienceImage.image.field.upload_to,
                                        os.path.basename(image))
                    ei = ExperienceImage(experience=experience, default=i == 0)
                    ei.image.save(path, ContentFile(fh.read()), True)
                    ei.image.name = os.path.join(
                        ExperienceImage.image.field.upload_to,
                        os.path.basename(image))
                    ei.save()

        print('Finished creating {} experiences'.format(kwargs['amount']))
Пример #19
0
def revision(repository, author):
    result = Revision(
        repository=repository,
        sha=uuid4().hex,
        author=author,
        message='\n\n'.join(get_paragraphs(2)),
        branches=['default', 'foobar'],
    )
    db.session.add(result)

    return result
Пример #20
0
def revision(repository, author, message=None):
    message = message or '\n\n'.join(get_paragraphs(2))
    result = Revision(
        repository=repository, sha=uuid4().hex, author=author,
        repository_id=repository.id, author_id=author.id,
        message=message,
        branches=['default', 'foobar'],
    )
    db.session.add(result)

    return result
Пример #21
0
 def submit_response(self):
     """
     Submit a response.
     """
     payload = json.dumps({
         'submission':
         u' '.join(loremipsum.get_paragraphs(random.randint(1, 10))),
     })
     self.client.post(self.handler_url('submit'),
                      data=payload,
                      headers=self._post_headers,
                      verify=False)
Пример #22
0
 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")
Пример #23
0
def entries_add_auto(mode, num):
    if not session.get('logged_in'):
        abort(401)

    db = get_db()
    for i in range(0, num):
        db.cursor().execute("insert into " + mode +
                            " (title, text) values ('" +
                            str(get_sentences(1, False)[0].replace(".", "")) +
                            "', '" + str(get_paragraphs(1, False)[0]) + "')")
    db.commit()
    flash('New ' + mode + ' automatic %d %s entrie%s successfully posted' %
          (num, mode, 's were' if (num > 1) else ' was'))
    return "OK"
Пример #24
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")
Пример #25
0
    def addProduct(self, cat, prodName, ext="jpg", price="1.1", stock="1", waitFor=1):
        self.driver.get(self.admin_url + self.addProductPath)

        select = Select(self.driver.find_element_by_id('id_category'))
        select.select_by_visible_text(cat)

        self.find_element_by_id("id_prodName",prodName, waitFor)
        imagePath =  os.path.join(self.imagesPath,cat.lower(),prodName+"."+ext)
        #self.driver.find_element_by_id("id_image").send_keys(imagePath)######
        self.find_element_by_id("id_image",imagePath)
        self.find_element_by_id("id_description",get_paragraphs(1)[0], waitFor)
        self.find_element_by_id("id_price",price, waitFor)
        self.find_element_by_id("id_stock",stock, waitFor)
        self.find_element_by_name("_save", waitFor)
Пример #26
0
def entries_add_auto(mode, num):
    if not session.get('logged_in'):
        abort(401)

    db = get_db()
    for i in range(0, num):
        db.execute(
            'insert into ' + mode +
            ' (title, text) values (?, ?)',
            [get_sentences(1, False)[0].replace(".", ""), get_paragraphs(1, False)[0]]
        )
    db.commit()
    flash('New ' + mode + ' automatic %d %s entrie%s successfully posted' %
          (num, mode, 's were' if (num > 1) else ' was'))
    return "OK"
Пример #27
0
 def peer_assess(self):
     """
     Assess a peer.
     """
     payload = json.dumps({
         'submission_uuid':
         self._submission_uuid('peer'),
         'options_selected':
         self.OPTIONS_SELECTED,
         'feedback':
         loremipsum.get_paragraphs(random.randint(1, 3)),
     })
     self.client.post(self.handler_url('peer_assess'),
                      data=payload,
                      headers=self._post_headers,
                      verify=False)
Пример #28
0
def generate_message(sender, recipient):
    """
    Generate a Lorem Ipsum email with sender and recipient.
    """
    if li is None:
        raise ValueError("Could not import loremipsum to generate messages!")

    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = recipient
    msg['Subject'] = li.get_sentences(1)[0]

    body = "\n\n".join(li.get_paragraphs(random.randint(1, 12)))
    msg.attach(MIMEText(body, 'plain'))

    return msg
Пример #29
0
def generate_message(sender, recipient):
    """
    Generate a Lorem Ipsum email with sender and recipient.
    """
    if li is None:
        raise ValueError("Could not import loremipsum to generate messages!")

    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = recipient
    msg['Subject'] = li.get_sentences(1)[0]

    body = "\n\n".join(li.get_paragraphs(random.randint(1,12)))
    msg.attach(MIMEText(body, 'plain'))

    return msg
Пример #30
0
def catch_all(path):

    parents = ['/']
    accumulated = ''
    for p in path.split('/'):
        if p:
            accumulated += '/' + p
            parents.append(str(accumulated))

    children = [('/{}/{}' if path else '/{}{}').format(path, i) for i in range(4)]

    return render_template('first.html',
                           parents=parents,
                           children=children,
                           title=loremipsum.generate_sentence(),
                           paragraphs=loremipsum.get_paragraphs(3))
Пример #31
0
    def _create_dummy_submission(self, student_item):
        """
        Create a dummy submission for a student.

        Args:
            student_item (dict): Serialized StudentItem model.

        Returns:
            str: submission UUID
        """
        answer = {'text': "  ".join(loremipsum.get_paragraphs(5))}
        submission = sub_api.create_submission(student_item, answer)
        workflow_api.create_workflow(submission['uuid'], STEPS)
        workflow_api.update_from_assessments(
            submission['uuid'], {'peer': {'must_grade': 1, 'must_be_graded_by': 1}}
        )
        return submission['uuid']
Пример #32
0
    def _create_dummy_submission(self, student_item):
        """
        Create a dummy submission for a student.

        Args:
            student_item (dict): Serialized StudentItem model.

        Returns:
            str: submission UUID
        """
        answer = {'text': "  ".join(loremipsum.get_paragraphs(5))}
        submission = sub_api.create_submission(student_item, answer)
        workflow_api.create_workflow(submission['uuid'], STEPS)
        workflow_api.update_from_assessments(
            submission['uuid'], {'peer': {'must_grade': 1, 'must_be_graded_by': 1}}
        )
        return submission['uuid']
Пример #33
0
def createTextBlocks(self, count=20):
    """
    """
    path = self.contentconfig.srconfig.textblocks
    for i in range(0, count):
        # random user
        docid = "tb_%d" % i
        # Generate random text for description
        
        d = chomsky(2)
        t = "<p>" + "</p><p>".join(get_paragraphs(3)) + "</p>"

        if not hasattr(path, docid):        
            path.invokeFactory(id=docid, type_name="SRTextBlock", title="Textblock %d" % i, description="")
            d = path._getOb(docid)
            d.text = RichTextValue(safe_unicode(t))
            d.reindexObject()
Пример #34
0
def change(project, **kwargs):
    if 'message' not in kwargs:
        kwargs['message'] = '\n\n'.join(get_paragraphs(2))

    if 'label' not in kwargs:
        diff_id = 'D{0}'.format(random.randint(1000, 1000000000000))
        kwargs['label'] = '{0}: {1}'.format(
            diff_id, kwargs['message'].splitlines()[0])[:128]
    else:
        diff_id = None

    if 'hash' not in kwargs:
        kwargs['hash'] = sha1(diff_id or uuid4().hex).hexdigest()

    kwargs.setdefault('repository', project.repository)

    result = Change(project=project, **kwargs)
    db.session.add(result)
    return result
Пример #35
0
def performance_test_1():
	u = User.objects.get(email='*****@*****.**')
	for x in range(50):
		bb = BitBook(title='A new bitbook number %s'%x, description=get_sentences(1)[0])
		bb.save()
		for y in range(100):
			bn = BitNote()
			bn.save()
			bf1 = BlogPost(title='blog post 1', body=''.join(get_paragraphs(10)))
			bf2 = Quote(title='a fancy qoute', body=get_sentences(1)[0], author='Author Aouthorski')
			bf3 = Rating(title='rating')
			bn.bitfields.append(bf1)
			bn.bitfields.append(bf2)
			bn.bitfields.append(bf3)
			bn.save()
			bn.save_to_bitbook(bitbook=bb)
		u.bitbooks.append(bb)
		u.save()
		print 'bb no %s'%x
    def test_post_large_quote(self, setup):
        """
        Test POST /quotes of a new entry with a large quote.
        """
        str1 = " "
        quote_text = str1.join(get_paragraphs(1000, True))
        logger.debug(f'Size of large quote: {len(quote_text)} characters.')

        response = setup.send_request.post(setup.session,
                                           '{"text": "' + quote_text + '"}')
        response_status_code = _get_status_code(response)
        response_ok = _get_key_value_from_response(response, 'ok')
        response_data = _get_key_value_from_response(response, 'data')
        response_text = _get_first_value_for_key_from_response_data(
            response_data, 'text')

        assert response_status_code == 201
        assert response_ok is True
        assert response_text == quote_text
Пример #37
0
    def create_revision(self, **kwargs):
        kwargs.setdefault('sha', uuid4().hex)
        if not kwargs.get('repository'):
            kwargs['repository'] = self.create_repo()
        kwargs['repository_id'] = kwargs['repository'].id

        if not kwargs.get('author'):
            kwargs['author'] = self.create_author()
        kwargs['author_id'] = kwargs['author'].id

        if not kwargs.get('message'):
            message = get_sentences(1)[0][:128] + '\n'
            message += '\n\n'.join(get_paragraphs(2))
            kwargs['message'] = message

        revision = Revision(**kwargs)
        db.session.add(revision)
        db.session.commit()

        return revision
Пример #38
0
def change(project, **kwargs):
    if 'message' not in kwargs:
        kwargs['message'] = '\n\n'.join(get_paragraphs(2))

    if 'label' not in kwargs:
        diff_id = 'D{0}'.format(random.randint(1000, 1000000000000))
        kwargs['label'] = '{0}: {1}'.format(
            diff_id, kwargs['message'].splitlines()[0]
        )[:128]
    else:
        diff_id = None

    if 'hash' not in kwargs:
        kwargs['hash'] = sha1(diff_id or uuid4().hex).hexdigest()

    kwargs.setdefault('repository', project.repository)

    result = Change(project=project, **kwargs)
    db.session.add(result)
    return result
Пример #39
0
    def peer_assess(self, continue_grading=False):
        """
        Assess a peer.

        Kwargs:
            continue_grading (bool): If true, simulate "continued grading"
                in which a student asks to assess peers in addition to the required number.

        """
        params = {
            'options_selected': self._select_random_options(),
            'overall_feedback': loremipsum.get_paragraphs(random.randint(1, 3)),
            'criterion_feedback': {}
        }

        if continue_grading:
            params['continue_grading'] = True

        payload = json.dumps(params)
        self.client.post(self.handler_url('peer_assess'), data=payload, headers=self._post_headers, verify=False)
Пример #40
0
def generate_record(i):
	# clone
	record = dict(model)

	record["age"] = randint(18,100)
	record["country"] = countries[randint(0,len(countries)-1)]
	record["surname"] = surnames[randint(0,len(surnames)-1)]
	record["text"] = "".join(loremipsum.get_paragraphs(randint(1,20)))
	#record["text"] = ""

	gender = randint(0,1)
	if gender is 1:
		#male
		record["firstname"] = male_firstnames[randint(0,len(male_firstnames)-1)]
	else:
		#female
		record["firstname"] = female_firstnames[randint(0,len(female_firstnames)-1)]

	record["email"] =  record["firstname"]+"."+record["surname"]+"@something.com"
	return record
Пример #41
0
def create_news_items(context, app, section, i):
    seq = i + 1
    item = api.content.create(
        container=app,
        type='News Item',
        title=LOREMIPSUM_TITLES[i],
    )
    item.section = create_relation(section.getPhysicalPath())
    item.description = ' '.join(loremipsum.get_sentences(2))
    item.text = RichTextValue(raw="\n\n".join(loremipsum.get_paragraphs(3)),
                              mimeType='text/plain',
                              outputMimeType='text/x-html-safe')
    img_name = '{:02d}.jpg'.format(seq)
    img_path = os.path.join('images', img_name)
    img_data = context.openDataFile(img_path).read()
    item.image = NamedBlobImage(data=img_data,
                                filename=img_name.decode('utf-8'))
    if i % 2:
        item.must_read = True
    item.setEffectiveDate('2016/09/{:02d}'.format(seq))
    api.content.transition(item, 'publish')
    item.reindexObject()
Пример #42
0
    def handle(self, *args, **options):
        blog = options.get('blog')
        quantity = options.get('quantity')
        blog_models = import_module('blog.blog%s.models' % blog)
        Post = blog_models.Post

        users = list(User.objects.all())
        categories = list(Category.objects.all())

        posts = []
        for i in range(int(quantity)):
            amount = int(random.random() * 4) + 1
            content = ' '.join(loremipsum.get_paragraphs(amount, True))
            title = loremipsum.generate_sentence(True)[2]
            posts.append(
                Post.objects.create(
                    author=random.choice(users),
                    category=random.choice(categories),
                    title=title[:60],
                    content=content,
                    approved=random.random() < 0.8,  # ~80% post approved
                    featured=random.random() < 0.1  # ~10% post approved
                )
            )

        tags = list(Tag.objects.all())

        for post in posts:
            for i in range(int(random.random() * 4)):
                comment = loremipsum.get_paragraph(True)
                blog_models.PostComment.objects.create(
                    post=post,
                    user=random.choice(users),
                    comment=comment,
                    approved=random.random() < 0.8  # ~80% post approved
                )

            for tag in random.choices(tags, k=random.choice([2, 3, 4])):
                post.tags.add(tag)
def create_items(number):
    ids = []
    items = []
    paragraphs = get_paragraphs(number)
    for i in xrange(number):
        item_id = "-%s-" % str(uuid.uuid4()).replace('-', '')
        ids.append({
            "residRef": item_id
        })
        items.append(
            {
                "resource": "items",
                "username": "******",
                "data": {
                    "firstcreated": "2013-11-11T11:11:11+00:00",
                    "text": paragraphs[i],
                    "item_type": "text"
                },
                "id_name": item_id
            }
        )
    return ids, items
Пример #44
0
def createTestDocuments(context, count):
    """
    """
    prefix = context.prefix or context.getId()
    count = int(count)
    for i in range(1, count):
        # random user
        u = int(round(random.random() + 1.0))
        uname = "%s_user%d" % (prefix, u)
        gname = "%s_Group%d" % (prefix, u)
        create_in_group = False
        if (int(round(random.random()))):
            create_in_group = True
        tn = int(random.random() * len(alldtypes))    
        etype = alldtypes[tn]
        
        path = None
        if create_in_group:
            path = context.content.Groups[gname]
        else:
            path = context.content.Members[uname.replace("-","--")]
        docid = "doc%d_%d" % (i, int(time.time()))
        # Generate random text for description
        
        d = chomsky(2)
        t = "<p>" + "</p><p>".join(get_paragraphs(3)) + "</p>"
        
        path.invokeFactory(id=docid, type_name="DPDocument", title="Document %d %s" % (i, uname), description=d)
        d = path._getOb(docid)
        d.docType = etype
        ILocalBehaviorSupport(d).local_behaviors = ['elan']
        d.text = RichTextValue(safe_unicode(t))
        s = int(round(random.random() + 1.0))
        if ELAN_APP in context.allSupportedApps():
            d.doc_extension(ELAN_APP).scenarios = ["scenario%d" % s]
        d.reindexObject()
Пример #45
0
    def peer_assess(self, continue_grading=False):
        """
        Assess a peer.

        Kwargs:
            continue_grading (bool): If true, simulate "continued grading"
                in which a student asks to assess peers in addition to the required number.

        """
        params = {
            'options_selected': self._select_random_options(),
            'overall_feedback': loremipsum.get_paragraphs(random.randint(1,
                                                                         3)),
            'criterion_feedback': {}
        }

        if continue_grading:
            params['continue_grading'] = True

        payload = json.dumps(params)
        self.client.post(self.handler_url('peer_assess'),
                         data=payload,
                         headers=self._post_headers,
                         verify=False)
Пример #46
0
 def test_description_is_very_long(self):
     paragraphs = get_paragraphs(25)
     lorem_ipsum = ', '.join(paragraphs)
     election = Election.objects.create(name='the name',
                                        description=lorem_ipsum)
     self.assertEquals(election.description, lorem_ipsum)
def get_comment() -> Comment:
    c = Comment()
    c.body = li.get_paragraphs(1)[0]
    c.date = "date"
    c.header = li.get_sentence()
    return c
Пример #48
0
def get_ipsum():
    n_paragraphs = int(request.args.get('paragraphs',5))
    content = get_paragraphs(n_paragraphs)
    return jsonify({"data":content})
Пример #49
0
['Ta\'izz', 13.373236, 44.033002], \
['San\'aa', 15.371458, 44.210937], \
['Hadramaut', 14.608361, 49.144142]]

#Create CSV upload file
fout = open("dummyushdata.csv", "wb")
csvout = csv.writer(fout, quoting=csv.QUOTE_NONNUMERIC)
headers = ["INCIDENT TITLE","DESCRIPTION","INCIDENT DATE", \
"LOCATION","LATITUDE", "LONGITUDE", "CATEGORY"]

csvout.writerow(headers)
for i in range(0, 100):
    row = []
    row += [get_sentences(1)]
    #Incident Title
    row += [get_paragraphs(1)]
    #Description
    row += [create_random_datetime("2014-01-01", "2014-12-30")]
    #incident date
    locpos = int(round((len(locs) - 1) * random.random()))
    row += [locs[locpos][0]]
    #location name
    row += [locs[locpos][1]]
    #latitude
    row += [locs[locpos][2]]
    #longitude
    numcats = int(1 + round((4) * random.random()))
    #Between 1 and 5
    catsused = []
    for i in range(0, numcats):
        catsused += [catids[int(round((len(catids) - 1) * random.random()))]]
Пример #50
0
 def test_get_paragraphs(self):
     """Test loremipsum.get_paragraphs function."""
     l = loremipsum.get_paragraphs(3)
     self.assertIsInstance(l, types.GeneratorType)
     self.assertEqual(len(list(l)), 3)
Пример #51
0
 def test_get_paragraphs(self):
     """Test loremipsum.get_paragraphs function."""
     l = loremipsum.get_paragraphs(3)
     self.assertIsInstance(l, types.GeneratorType)
     self.assertEqual(len(list(l)), 3)
Пример #52
0
    def handle(self, *args, **options):
        """
        Execute the command.

        Args:
            course_id (unicode): The ID of the course to create submissions for.
            item_id (unicode): The ID of the item in the course to create submissions for.
            num_submissions (int): Number of submissions to create.
        """
        if len(args) < 3:
            raise CommandError('Usage: create_oa_submissions <COURSE_ID> <ITEM_ID> <NUM_SUBMISSIONS>')

        course_id = unicode(args[0])
        item_id = unicode(args[1])

        try:
            num_submissions = int(args[2])
        except ValueError:
            raise CommandError('Number of submissions must be an integer')

        print u"Creating {num} submissions for {item} in {course}".format(
            num=num_submissions, item=item_id, course=course_id
        )

        for sub_num in range(num_submissions):

            print "Creating submission {num}".format(num=sub_num)

            # Create a dummy submission
            student_item = {
                'student_id': uuid4().hex[0:10],
                'course_id': course_id,
                'item_id': item_id,
                'item_type': 'openassessment'
            }
            submission_uuid = self._create_dummy_submission(student_item)
            self._student_items.append(student_item)

            # Create a dummy rubric
            rubric, options_selected = self._dummy_rubric()

            # Create peer assessments
            for num in range(self.NUM_PEER_ASSESSMENTS):
                print "-- Creating peer-assessment {num}".format(num=num)

                scorer_id = 'test_{num}'.format(num=num)

                # The scorer needs to make a submission before assessing
                scorer_student_item = copy.copy(student_item)
                scorer_student_item['student_id'] = scorer_id
                scorer_submission_uuid = self._create_dummy_submission(scorer_student_item)

                # Retrieve the submission we want to score
                # Note that we are NOT using the priority queue here, since we know
                # exactly which submission we want to score.
                peer_api.create_peer_workflow_item(scorer_submission_uuid, submission_uuid)

                # Create the peer assessment
                peer_api.create_assessment(
                    scorer_submission_uuid,
                    scorer_id,
                    options_selected, {}, "  ".join(loremipsum.get_paragraphs(2)),
                    rubric,
                    self.NUM_PEER_ASSESSMENTS
                )

            # Create a self-assessment
            print "-- Creating self assessment"
            self_api.create_assessment(
                submission_uuid, student_item['student_id'],
                options_selected, rubric
            )
Пример #53
0
def lorem(paragraphs=5):
    return '\n\n'.join(
        '<p>{}</p>'.format(par)
        for par in loremipsum.get_paragraphs(paragraphs, start_with_lorem=True)
    )
Пример #54
0
def gen_para():
    return str((get_paragraphs(1)[0])).lower() 
Пример #55
0
  def handle(self, *args, **options):
    start_time = datetime.now()
    #Заполнение юзеров
    for user_id in range(1, users_count + 1):
      user = CustomUser(
          avatar='default.jpg',
          password=make_password("password"),
          last_login=self.random_date(),
          is_superuser=False,
          username="******" % (user_id),
          first_name="",
          last_name="",
          email="",
          is_staff=False,
          is_active=True,
          date_joined=datetime(2015, 1, 1, 1, 0, 0, 0, pytz.UTC)
      )
      self.stdout.write("User#%d" % user_id)
      user.save()
    # Заполнение вопросов
    for question_id in range(1, questions_count + 1):
      text = ''
      for i in get_paragraphs(randint(1, 4)):
        text += i

      question = Question(
          title=get_sentence(),
          content=text,
          author_id=randint(1, users_count),
          created=self.random_date(),
          rating=0
      )
      self.stdout.write("Question#%d" % question_id)
      question.save()

    # Заполнение ответов
    for answer_id in range(1, answers_count + 1):
      text = ''
      for i in get_paragraphs(randint(1, 2)):
        text += i

      answer = Answer(
          id=answer_id,
          content=text,
          author_id=randint(1, users_count),
          created=self.random_date(),
          question_id=randint(1, questions_count),
          rating=0
      )

      self.stdout.write("Answer#%d" % answer_id)
      answer.save()

    # Заполнение тэгов
    words = open('polls/words', 'r')
    for tag_id in range(1, tags_count + 1):
      tag = Tag(title=words.readline()[:-1])
      tag.save()
    words.close()


   # Заполнение лайков вопросов
    for like_id in range(1, votes_count):
      l_value = randint(0, 1)
      if l_value == 0:
        l_value = -1
      rand_user = randint(1, users_count)
      rand_question = randint(1, questions_count)
      try:
        like = LikeForQuestion(user_id=rand_user, value=l_value, question_related_id=rand_question)
        like.save()
        self.stdout.write("Like#%d" % like_id)
        quest = Question.objects.get(id=rand_question)
        quest.rating = str(l_value + quest.rating)
        quest.save()
      except django.db.IntegrityError:
          pass


    # Для ответов
    for like_id in range(1, votes_count):
      l_value = randint(0, 1)
      if l_value == 0:
        l_value = -1
      rand_user = randint(1, users_count)
      rand_question = randint(1, questions_count)
      try:
        like = LikeForAnswers(user_id=rand_user, value=l_value, answer_related_id=rand_question)
        like.save()
        self.stdout.write("Like#%d" % like_id)
        quest = Answer.objects.get(id=rand_question)
        quest.rating = str(l_value + quest.rating)
        quest.save()
      except django.db.IntegrityError:
          pass

    # Добавление тегов к вопросам
    for question_id in range(1, questions_count + 1):
      question = Question.objects.get(pk=question_id)
      self.stdout.write("Linking tags#%d" % question_id)
      for i in range(1, 4):
        question.tags.add(Tag.objects.get(pk=randint(1, tags_count)))

    end_time = datetime.now()
    self.stdout.write(
        'Database filled successfully' + str(end_time - start_time))
Пример #56
0
##BOILERPLATE_COPYRIGHT
##BOILERPLATE_COPYRIGHT_END

'''

from loremipsum import get_paragraphs, get_sentences

from random import randint, sample

entries = []

all_tags = ['Foo', 'Bar', 'Snaz', 'Loop', 'Core', 'Nugget', 'Piddle', 'Snappy']

for i in range(randint(50, 90)):
    title = get_sentences(1)[0]
    p = get_paragraphs(randint(4, 20))
    index = randint(1,3)
    entry = '\n\n'.join(p[0:index])
    entry = entry + "<!--break-->" + '\n\n'.join(p[index:])
    weight = randint(-5, 5)
    url = None
    if randint(0,1):
        url = '_'.join(get_sentences(1)[0][:-1].split())

    tags = None
    if randint(0,5) > 1:
        tags = sample(all_tags, randint(1, len(all_tags)-1))
        tags.append('Everything')
    e = ( "%s (%d)" % (title, i), entry, weight, url, tags, False)
    entries.append(e)
Пример #57
0
"""

from loremipsum import get_sentence, get_paragraph, get_paragraphs
from random import randint, sample

TAGS = ['matlab', 'python', 'open source']
AUTHOR = 'Firstname Lastname <*****@*****.**>'

randyear  = lambda: randint(2013, 2015)
randmonth = lambda: randint(1, 12)
randday   = lambda: randint(1, 28)

randtitle = lambda: get_sentence(False)
randsummary = lambda: get_paragraph(False)
randtag = lambda: sample(TAGS, 1)[0]
randcontent = lambda: '\n\n'.join(get_paragraphs(randint(3,4)))

def generate_date():
    return '{}-{:02}-{:02}'.format(randyear(), randmonth(), randday())

def generate_article():
    title = randtitle()
    slug = title.replace('.', '').replace(' ', '-')
    info = dict(
        title=title,
        slug=slug,
        date=generate_date(),
        tags=randtag(),
        author=AUTHOR,
        summary=randsummary()
    )
#Make list of locations: name, latitude, longitude
locs = [ \
['Ibb', 13.992356, 44.164838], \
['Ta\'izz', 13.373236, 44.033002], \
['San\'aa', 15.371458, 44.210937], \
['Hadramaut', 14.608361, 49.144142]];

#Create CSV upload file
fout = open("dummyushdata.csv", "wb")
csvout = csv.writer(fout, quoting=csv.QUOTE_NONNUMERIC)
headers = ["INCIDENT TITLE","DESCRIPTION","INCIDENT DATE", \
"LOCATION","LATITUDE", "LONGITUDE", "CATEGORY"];

csvout.writerow(headers)
for i in range(0,100):
	row = [];
	row += [get_sentences(1)]; #Incident Title
	row += [get_paragraphs(1)]; #Description
	row += [create_random_datetime("2014-01-01","2014-12-30")]; #incident date
	locpos = int(round((len(locs)-1)*random.random()));
	row += [locs[locpos][0]];#location name
	row += [locs[locpos][1]];#latitude
	row += [locs[locpos][2]];#longitude
	numcats = int(1+round((4)*random.random())); #Between 1 and 5
	catsused = []
	for i in range(0,numcats):
		catsused += [catids[int(round((len(catids)-1)*random.random()))]]
	row += [",".join(catsused)]; #category
	csvout.writerow(row)
fout.close()