def test_add_existed_member_with_invitation(self): self.account = AccountFactory() self.admin = AdminFactory(accounts=[self.account]) self.login_admin() old_acc = list(self.user.accounts.all().values_list('id', flat=True)) old_acc.append(get_current_account(self).id) url = reverse('member_create', kwargs={'url': get_current_account(self).url}) data = { 'first_name': lorem_ipsum.words(1, False).capitalize()[:50], 'last_name': lorem_ipsum.words(1, False).capitalize()[:50], 'email': self.user.email, 'password': User.objects.make_random_password(), 'date_joined_board': '{:%b. %d, %Y}'.format(timezone.now()), 'timezone': us_timezones[0], 'account': get_current_account(self), 'role': Membership.ROLES.member, 'invitation': True } response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, _('Member was added successfully.')) self.assertItemsEqual( list(self.user.accounts.all().values_list('id', flat=True)), old_acc)
def test_notifications_pagination(self): Notification.objects.all().delete() for i in range(0,53): notification = { 'title': words(2, False), 'description': words(6, False), 'recipient': User.objects.get(username='******'), 'app': 'game', 'key': 'foo%s' % i, } Notification(**notification).save() self.client.login(username='******', password='******') response = self.client.get(reverse('notifications_api_list'), format='json') self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data['results']), 5) self.assertEqual(response.data['count'], 53) self.assertEqual(response.data['total_pages'], 11) self.assertEqual(response.data['current_page'], 1) response = self.client.get(reverse('notifications_api_list'), {'page': 5}, format='json') self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data['results']), 5) self.assertEqual(response.data['count'], 53) self.assertEqual(response.data['total_pages'], 11) self.assertEqual(response.data['current_page'], 5) response = self.client.get(reverse('notifications_api_list'), {'page': 11}, format='json') self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data['results']), 3) self.assertEqual(response.data['count'], 53) self.assertEqual(response.data['total_pages'], 11) self.assertEqual(response.data['current_page'], 11)
def test_member_permission(self): self.account = AccountFactory() user_member = UserFactory(accounts=[self.account]) self.login_member(user_member.email) data = { 'role': Membership.ROLES.chair, 'email': u'{}_{}@example.com'.format(self.account.id, lorem_ipsum.words(1, False)), 'first_name': lorem_ipsum.words(1, False).capitalize()[:50], 'last_name': lorem_ipsum.words(1, False).capitalize()[:50], 'password': '******', 'date_joined_board': '{:%b. %d, %Y}'.format(timezone.now()), 'timezone': us_timezones[0], 'account': get_current_account(self), 'invitation': True } url = reverse('member_create', kwargs={'url': get_current_account(self).url}) response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 403) url = reverse('profiles:edit', kwargs={'pk': self.user.pk}) response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 404)
def test_update(self): experiment = ExperimentFactory(lab=self.lab, owners=[self.owner.pk]) url = reverse('experiments:update', kwargs={'lab_pk': self.lab.pk, 'pk': experiment.pk}) data = { 'owners': [self.owner.pk], 'start': timezone.now().strftime('%m/%d/%Y %H:%M'), 'end': timezone.now().strftime('%m/%d/%Y %H:%M'), 'description': lorem_ipsum.words(2), 'title': lorem_ipsum.words(2), 'status': Experiment.STATUS[0][0] } resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertContains(resp, _('Login')) self.client.login(username=self.owner.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertEqual(Experiment.objects.count(), 1) experiment = Experiment.objects.get(pk=experiment.pk) self.assertEqual(experiment.description, data['description']) self.client.login(username=self.member.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.client.login(username=self.guest.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 403) self.client.login(username=self.user4.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 403)
class MeetingFactory(factory.DjangoModelFactory): class Meta: model = Meeting name = lorem_ipsum.words(4, True) description = lorem_ipsum.words(8, True) @factory.sequence def start(n): return timezone.now() + timedelta(days=n) @factory.lazy_attribute_sequence def end(self, n): return self.start + timedelta(hours=n) location = lorem_ipsum.words(5, True) status = 1 @factory.lazy_attribute def account(self): return Account.objects.order_by('?')[0] @factory.lazy_attribute def committee(self): return Committee.objects.filter( account_id=self.account.id).order_by('?')[0]
def create_blogpost(author): data = { 'title': lorem_ipsum.words(random.randint(5, 10)), 'content': ''.join(lorem_ipsum.words(random.randint(10, 30)))[:500], 'publication': now(), 'author': author, } return BlogPost.objects.create(**data)
def create_room(zosia): data = { 'name': lorem_ipsum.words(1), 'description': lorem_ipsum.words(3), 'capacity': random.randint(1, 6), 'zosia': zosia, } return Room.objects.create(**data)
def extra_data(self): return { 'id': lorem_ipsum.words(1, False), 'team_id': lorem_ipsum.words(1, False), 'access_token': lorem_ipsum.words(1, False), 'bot': { 'bot_user_id': 'test_id', 'bot_access_token': 'access_token' } }
def test_chairperson_permission(self): self.account = AccountFactory() user_chairperson = ChairpersonFactory(accounts=[self.account]) self.login_member(user_chairperson.email) data = { 'role': Membership.ROLES.chair, 'email': u'{}_{}@example.com'.format(self.account.id, lorem_ipsum.words(1, False)), 'first_name': lorem_ipsum.words(1, False).capitalize()[:50], 'last_name': lorem_ipsum.words(1, False).capitalize()[:50], 'password': '******', 'date_joined_board': '{:%b. %d, %Y}'.format(timezone.now()), 'timezone': us_timezones[0], 'account': get_current_account(self), 'invitation': True } url = reverse('member_create', kwargs={'url': get_current_account(self).url}) response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, _('Member was added successfully.')) url = reverse('profiles:edit', kwargs={'pk': self.membership.pk}) data['email'] = u'{}_{}@example.com'.format( self.account.id, lorem_ipsum.words(1, False)), response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, _('Profile was changed successfully.')) self.assertEqual(Membership.ROLES.chair, Membership.objects.get(pk=self.membership.pk).role) url = reverse( 'profiles:edit', kwargs={'pk': user_chairperson.get_membership(self.account).pk}) data['role'] = Membership.ROLES.admin data['email'] = u'{}_{}@example.com'.format( self.account.id, lorem_ipsum.words(1, False)), response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, _('Profile was changed successfully.')) self.assertEqual( Membership.ROLES.chair, Membership.objects.get( pk=user_chairperson.get_membership(self.account).pk).role)
def test_create(self): url = reverse('news:create', kwargs={'url': get_current_account(self).url}) data = { 'title': lorem_ipsum.words(2, False), 'text': lorem_ipsum.words(5, True), 'is_publish': True } response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, 'News was added successfully.')
def test_manager(self): notification = { 'title': words(2, False), 'description': words(6, False), 'recipient': User.objects.get(username='******'), 'app': 'game', 'key': 'bar', } nb = len(Notification.objects.get_or_create(**notification)) self.assertEqual(nb, 1) nb = len(Notification.objects.get_or_create(**notification)) self.assertEqual(nb, 0)
def test_manager_recipients_list(self): notification = { 'title': words(2, False), 'description': words(6, False), 'recipients': User.objects.all()[:2], 'app': 'game', 'key': 'bar', } nb = len(Notification.objects.get_or_create(**notification)) self.assertEqual(nb, 2) nb = len(Notification.objects.get_or_create(**notification)) self.assertEqual(nb, 0)
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 accounts(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return # A list of groups were passed in, use them for account in extracted: Membership.objects.create( user=self, account=account, role=Membership.ROLES.chair, first_name=lorem_ipsum.words(1, False).capitalize(), last_name=lorem_ipsum.words(1, False).capitalize())
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 test_create(self): url = reverse('committees:create', kwargs={'url': get_current_account(self).url}) data = { 'name': lorem_ipsum.words(2, False).capitalize()[:50], 'chairman': self.membership_admin.id, 'members': [self.membership_admin.id, self.membership.id], 'summary': lorem_ipsum.words(5, True), 'description': lorem_ipsum.words(20, True), 'account': get_current_account(self) } response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Committee was added successfully.')
def test_update_wrong(self): user = UserFactory(accounts=[self.account]) self.login_member(user.email) url = reverse('news:edit', kwargs={ 'pk': self.news.pk, 'url': get_current_account(self).url }) data = { 'title': lorem_ipsum.words(2, False), 'text': lorem_ipsum.words(5, True), 'is_publish': True } response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 403)
def test_update(self): url = reverse('news:edit', kwargs={ 'pk': self.news.pk, 'url': get_current_account(self).url }) data = { 'title': lorem_ipsum.words(2, False), 'text': lorem_ipsum.words(5, True) } response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, 'News was updated successfully.') self.assertEqual( News.objects.get(pk=self.news.pk).title, data['title'])
def test_common_words_in_string(self): """words(n) starts with the 19 standard lorem ipsum words for n > 19.""" self.assertTrue( words(25).startswith( 'lorem ipsum dolor sit amet consectetur adipisicing elit sed ' 'do eiusmod tempor incididunt ut labore et dolore magna aliqua' ))
def create_classification_project(self, owner, research_project, collections=None, roles=None, **kwargs): if 'name' not in kwargs: name = words(3, common=False) else: name = kwargs['nmae'] params = { 'name': name, 'research_project': research_project, 'owner': owner } params.update(kwargs or {}) project = ClassificationProject.objects.create(**params) if collections: project.collections = collections if roles: for user, role_level in roles: ClassificationProjectRole.objects.create( classification_project=project, user=user, name=role_level) return project
def test_resource_create_preselected(self): """ Using create view create storage.Resource model instance After resource is created user is redirected to details page - version where user preselect existing file.""" deployment = self.create_deployment(owner=self.alice) image_file = os.path.join(self.SAMPLE_MEDIA_PATH, 'image_1.jpg') temp_file = get_external_resources_path(self.alice.username, 'image_1.jpg') temp_path = os.path.dirname(temp_file) # When test is run as single we need to make sure that copying file # is made to existing directory if not os.path.exists(temp_path): os.makedirs(temp_path) shutil.copyfile(image_file, temp_file) url = self.get_resource_create_url() self.login_alice() name = words(count=5, common=False) params = { 'name': name, 'date_recorded': '06.06.2015 06:06:06', 'preselected_file': 'image_1.jpg', 'status': ResourceStatus.PRIVATE, 'deployment': deployment.pk } response = self.client.post(url, params) self.assertEqual(response.status_code, 302, response.status_code) self.assertTrue( Resource.objects.filter(name=name, date_recorded=datetime.datetime( 2015, 6, 6, 6, 6, 6), status=ResourceStatus.PRIVATE, deployment=deployment).exists())
def create_room(number): if random.random() < 0.1: data = { 'name': f"Room nr. {number}", 'description': lorem_ipsum.words(random.randint(3, 6)), 'beds_double': 1, 'available_beds_double': 1, } else: data = { 'name': f"Room nr. {number}", 'description': lorem_ipsum.words(random.randint(3, 6)), 'beds_single': random.randint(1, 6), 'available_beds_single': random.randint(1, 6), } return Room.objects.create(**data)
def test_update_lab(self): data = { 'name': lorem_ipsum.words(1, False), 'investigator': [self.owner.pk], 'members': [self.member.pk], 'guests': [self.guest.pk] } lab = LabFactory(**data) url = reverse('labs:update', kwargs={'lab_pk': lab.pk}) data['name'] = name = 'test' resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertContains(resp, _('Login')) self.client.login(username=self.owner.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertEqual(Lab.objects.count(), 1) self.assertEqual(Lab.objects.first().name, name) self.client.login(username=self.member.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.client.login(username=self.guest.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 403) self.client.login(username=self.user4.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 403)
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 test_negative_words(self): """words(n) returns n + 19 words, even if n is negative.""" self.assertEqual( words(-5), "lorem ipsum dolor sit amet consectetur adipisicing elit sed do " "eiusmod tempor incididunt ut", )
def test_create(self): url = reverse('collections:create', kwargs={'lab_pk': self.lab.pk}) data = { 'title': lorem_ipsum.words(3, False), 'units': [unicode(unit.pk) for unit in self.units], 'owners': [self.owner.pk], } resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertContains(resp, _('Login')) self.client.login(username=self.owner.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertEqual(Collection.objects.count(), 1) self.client.login(username=self.member.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertContains(resp, _(u'You have not permission to add this units {} in your ' u'collection'.format(','.join([unit.__unicode__() for unit in self.units]))), 1) self.assertEqual(Collection.objects.count(), 1) self.client.login(username=self.guest.email, password='******') resp = self.client.post(url, data, follow=True) self.assertContains(resp, _(u'Select a valid choice. {} is not one of the available choices.'.format(self.units[0].pk)), 1) self.assertEqual(Collection.objects.count(), 1) self.client.login(username=self.user4.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 403) self.assertEqual(Collection.objects.count(), 1)
def test_latest_minichat(self): Message.objects.all().delete() for i in range(0,57): Message(user=self.author, text=words(5, False)).save() Message(user=self.author, text='Last message').save() response = self.client.get(reverse('minichat-api-latest-list'), format='json') self.assertEqual(response.status_code, 200) self.assertEqual(response.data['count'], 58) self.assertEqual(len(response.data['results']), 10) first_message = response.data['results'][0] # Striclty check the fields to avoir extra disclosure (field id is not sent) self.assertEqual(list(first_message.keys()), ['user', 'text', 'date']) # Striclty check the fields to avoir extra disclosure (we should only send username # and profile, not password, email, ...) self.assertEqual(list(first_message['user'].keys()), ['username', 'profile', 'get_absolute_url']) # Striclty check the fields to avoir extra disclosure (we should only send avatar, # not last_visit, ...) self.assertEqual(list(first_message['user']['profile'].keys()), ['avatar']) self.assertEqual(first_message['text'], 'Last message')
def test_profile_change(self): """Update user profile""" logged_in = self.client.login( username=self.user.username, password=self.passwd ) self.assertTrue(logged_in) first_name = 'Amanda' last_name = 'Amandasia' institution = 'Hogwart' about_me = words(5) self.client.post( self.profile_url, data={ 'first_name': first_name, 'last_name': last_name, 'institution': institution, 'about_me': about_me, 'update-profile': '' } ) user = User.objects.get(pk=self.user.pk) profile = user.userprofile self.assertEqual(user.first_name, first_name) self.assertEqual(user.last_name, last_name) self.assertEqual(profile.institution, institution) self.assertEqual(profile.about_me, about_me)
def get_random_article(): """ Method returns random article dictionary with content, description and title. """ return { 'content': lorem.paragraph(), 'description': lorem.sentence(), 'title': lorem.words(count=4, common=False).capitalize(), }
def create_research_project(self, owner, status=None, collections=None, roles=None, name=None): if status is None: status = ResearchProjectStatus.APPROVED name = name or words(3, common=False) acronym = name[:3] project = ResearchProject.objects.create(name=name, acronym=acronym, status=status, owner=owner) if collections: project.collections = collections if roles: for user, role_level in roles: ResearchProjectRole.objects.create(project=project, user=user, name=role_level) return project
def create_resource(self, owner, status=None, file_content=None, managers=None, **resource_kwargs): status = status or ResourceStatus.ON_DEMAND if not file_content: file_path = os.path.join(self.SAMPLE_MEDIA_PATH, 'image_1.jpg') with open(file_path) as handler: file_content = handler.read() file_name = u"{name}.png".format(name=create_hashcode()) params = { 'name': words(3, common=False), 'file': SimpleUploadedFile(file_name, file_content), 'date_recorded': now(), 'status': status, 'owner': owner } params.update(**resource_kwargs) resource = Resource.objects.create(**params) if managers: resource.managers = managers return resource
def test_create_with_perm(self): experiment1 = ExperimentFactory(lab=self.lab, owners=[self.owner.pk], editors=[self.member.pk], viewers=[self.guest.pk]) unit1 = UnitFactory(lab=self.lab, user=self.owner, experiments=[experiment1]) experiment2 = ExperimentFactory(lab=self.lab, owners=[self.member.pk]) unit2 = UnitFactory(lab=self.lab, user=self.member, experiments=[experiment2]) url = reverse('collections:create', kwargs={'lab_pk': self.lab.pk}) data = { 'title': lorem_ipsum.words(3, False), 'units': [unicode(unit1.pk), unicode(unit2.pk)], 'owners': [self.owner.pk], } self.client.login(username=self.owner.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertEqual(Collection.objects.count(), 1) self.client.login(username=self.member.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertEqual(Collection.objects.count(), 2) self.client.login(username=self.guest.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertContains(resp, _(u'Select a valid choice. {} is not one of the available choices.'.format(unit2.pk)), 1) self.assertEqual(Collection.objects.count(), 2) self.client.login(username=self.user4.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 403) self.assertEqual(Collection.objects.count(), 2)
def test_negative_words(self): """words(n) returns n + 19 words, even if n is negative.""" self.assertEqual( words(-5), 'lorem ipsum dolor sit amet consectetur adipisicing elit sed do ' 'eiusmod tempor incididunt ut' )
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 test_resource_create_upload(self): """ Using create view create storage.Resource model instance After resource is created user is redirected to details page - version where user upload file.""" deployment = self.create_deployment(owner=self.alice) image_file = os.path.join(self.SAMPLE_MEDIA_PATH, 'image_1.jpg') url = self.get_resource_create_url() self.login_alice() name = words(count=5, common=False) with open(image_file) as file_handler: params = { 'name': name, 'date_recorded': '08.08.2015 06:06:06', 'file': file_handler, 'status': ResourceStatus.PRIVATE, 'deployment': deployment.pk } response = self.client.post(url, params) self.assertEqual(response.status_code, 302, response.status_code) self.assertTrue( Resource.objects.filter(name=name, date_recorded=datetime.datetime( 2015, 8, 8, 6, 6, 6), status=ResourceStatus.PRIVATE, deployment=deployment).exists())
def test_dashboard_recent_save_meeting_create_without_notify(self): self.login_admin() self.account.send_notification = False self.account.save() self.client.get( reverse('meetings:create', kwargs={'url': self.account.url})) agenda = DocumentFactory(user=self.admin, type=Document.AGENDA) minutes = DocumentFactory(user=self.admin, type=Document.MINUTES) other_docs = DocumentFactory(user=self.admin, type=Document.OTHER) docs = '{},{},{}'.format(agenda.id, minutes.id, other_docs.id) date = timezone.now() + timedelta(days=2) data = { 'name': lorem_ipsum.words(2, False).capitalize()[:50], 'date': date.date().strftime("%b. %d, %Y"), 'time_start': date.time().strftime("%I:%M %p"), 'time_end': (date + timedelta(hours=3)).time().strftime("%I:%M %p"), 'location': '709 Sixth Street, Newark, DE 19711', 'committee': self.committee.id, 'account': self.account, 'uploaded': docs } resp = self.client.post(reverse('meetings:create', kwargs={'url': self.account.url}), data, follow=True) self.assertContains(resp, 'Meeting was added successfully.') self.assertTrue(len(RecentActivity.objects.all()) > 0) for item in RecentActivity.objects.all(): self.assertEqual(item.content_object.name, data['name']) self.assertEqual(len(mail.outbox), 0)
def setUp(self): super(CollectionRequestTestCase, self).setUp() self.summon_alice() self.summon_ziutek() self.resource = self.create_resource(owner=self.alice) self.resource2 = self.create_resource(owner=self.alice) self.collection = self.create_collection( owner=self.alice, resources=[self.resource, self.resource2]) self.research_project = self.create_research_project(owner=self.ziutek) self.message = Message.objects.create( subject=words(3), text=paragraph(), user_from=self.ziutek, user_to=self.alice, message_type=MessageType.COLLECTION_REQUEST) self.collection_request = CollectionRequest.objects.create( name='collection request', project=self.research_project, user=self.alice, user_from=self.ziutek, message=self.message) self.collection_request.collections.add(self.collection)
def setUp(self): self.old_setting = settings.FILEMANAGER_UPLOAD_ROOT settings.FILEMANAGER_UPLOAD_ROOT += '_test/' self.owner = UserFactory() url = reverse('labs:create') data = { 'name': lorem_ipsum.words(1, False), 'investigator': [self.owner.pk], # 'members': [self.member.pk], } self.client.login(username=self.owner.email, password='******') resp = self.client.post(url, data, follow=True) self.lab = Lab.objects.get(name=data['name']) with open(os.path.join(settings.FILEMANAGER_UPLOAD_ROOT, unicode(self.lab.pk) + '/', 'testfile1.txt'), 'w') as f: f.write('test file content') inner_directory = os.path.join(settings.FILEMANAGER_UPLOAD_ROOT, unicode(self.lab.pk) + '/', 'test dir') if not os.path.exists(inner_directory): os.makedirs(inner_directory) with open(os.path.join(inner_directory, 'testfile2.txt'), 'w') as f: f.write('test file content in dir') self.client.logout()
def test_recent_comment_activity_view(self): experiment = ExperimentFactory(lab=self.lab, owners=[self.owner.pk], editors=[self.guest.pk]) url = reverse('dashboard:comment-activity', kwargs={'lab_pk': self.lab.pk}) resp = self.client.get(url) self.assertNotEqual(resp.status_code, 200) self.client.login(username=self.owner.email, password='******') resp = self.client.get(url) self.assertContains(resp, u'timeline') # Add comment text = lorem_ipsum.words(2) comment_url = reverse('comment:api-list', kwargs={ 'lab_pk': self.lab.pk, 'instance_type': 'experiment', 'object_id': experiment.pk, }) data = { 'text': text, 'instance_type': 'experiment', 'object_id': experiment.pk, } resp = self.client.post(comment_url, data, format='json') self.assertEqual(resp.status_code, 201) resp = self.client.get(url) self.assertContains(resp, title(self.owner.full_name)) self.assertContains(resp, text)
def update_livelobg_plugin_content(plugin, publish=True): plugin_text = words(count=3, common=False) plugin.body = plugin_text plugin.publish = publish plugin.save() __, admin = plugin.get_plugin_instance() admin.save_model(get_request("/"), plugin, None, None) return plugin, admin, plugin_text
def test_event_committee_created(self, mock_track_event): # Create Committee url = reverse('committees:create', kwargs={'url': get_current_account(self).url}) data = { 'name': lorem_ipsum.words(2, False).capitalize()[:50], 'chairman': self.membership_admin.id, 'members': [self.membership_admin.id, self.membership.id], 'summary': lorem_ipsum.words(5, True), 'description': lorem_ipsum.words(20, True), 'account': get_current_account(self) } response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) # Signal fired self.assertEquals(mock_track_event.call_count, 1)
def test_change_owners_by_editor(self): """ Check Editors can't change owners in experiments """ collection = CollectionFactory(lab=self.lab, owners=[self.owner.pk], editors=[self.member.pk], user=self.owner, units=self.units) url = reverse('collections:update', kwargs={'lab_pk': self.lab.pk, 'pk': collection.pk}) data = { 'owners': [self.member.pk], 'editors': [self.owner.pk], 'description': lorem_ipsum.words(2), 'title': lorem_ipsum.words(2), } self.client.login(username=self.member.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'You have not permission change owners', 1) self.assertEqual(Collection.objects.first().owners, [self.owner])
def create_fake_data(): # create some fake data to make sure we need to paginate if Person.objects.all().count() < 50: countries = list(Country.objects.all()) + [None] Person.objects.bulk_create([ Person(name=words(3, common=False), country=choice(countries)) for i in range(50) ])
def setUp(self): self.owner = UserFactory() self.member = UserFactory() self.guest = UserFactory() self.user4 = UserFactory() data = {"name": lorem_ipsum.words(1, False), "investigator": [self.owner.pk], "members": [self.member.pk]} self.lab = LabFactory(**data)
def test_common_words_in_string(self): """words(n) starts with the 19 standard lorem ipsum words for n > 19.""" self.assertTrue( words(25).startswith( 'lorem ipsum dolor sit amet consectetur adipisicing elit sed ' 'do eiusmod tempor incididunt ut labore et dolore magna aliqua' ) )
def _generate_tags(self): """Сгенерировать теги для нескольких случайных фотографий.""" tag_words = words(self.number_of_tags).split() for photo in Photo.objects.order_by('?')[:1000]: sample_length = random.randrange( 0, self.average_tags_per_photo * 2) if sample_length: selected_tags = random.sample(tag_words, sample_length) photo.update_tags(selected_tags)
def test_recent_all_activity_view(self): experiment = ExperimentFactory(lab=self.lab, owners=[self.owner.pk], editors=[self.guest.pk]) url = reverse('dashboard:all-activity', kwargs={'lab_pk': self.lab.pk}) resp = self.client.get(url) self.assertNotEqual(resp.status_code, 200) self.client.login(username=self.owner.email, password='******') resp = self.client.get(url) self.assertContains(resp, u'timeline') #Update experiment exp_url = reverse('experiments:update', kwargs={'lab_pk': self.lab.pk, 'pk': experiment.pk}) data = { 'owners': [self.owner.pk], 'start': experiment.start.strftime('%m/%d/%Y %H:%M'), 'end': experiment.end.strftime('%m/%d/%Y %H:%M'), 'description': lorem_ipsum.words(2), 'title': experiment.title, 'status': experiment.status } resp = self.client.post(exp_url, data, follow=True) resp = self.client.get(url) self.assertContains(resp, title(self.owner.full_name)) self.assertContains(resp, experiment.title) # Add comment text = lorem_ipsum.words(2) comment_url = reverse('comment:api-list', kwargs={ 'lab_pk': self.lab.pk, 'instance_type': 'experiment', 'object_id': experiment.pk, }) data = { 'text': text, 'instance_type': 'experiment', 'object_id': experiment.pk, } resp = self.client.post(comment_url, data, format='json') self.assertEqual(resp.status_code, 201) resp = self.client.get(url) self.assertContains(resp, title(self.owner.full_name)) self.assertContains(resp, text)
def test_change_owners_by_editor(self): """ Check Editors can't change owners in experiments """ experiment = ExperimentFactory(lab=self.lab, owners=[self.owner.pk], editors=[self.member.pk]) url = reverse('experiments:update', kwargs={'lab_pk': self.lab.pk, 'pk': experiment.pk}) data = { 'owners': [self.member.pk], 'editors': [self.owner.pk], 'start': timezone.now().strftime('%m/%d/%Y %H:%M'), 'end': timezone.now().strftime('%m/%d/%Y %H:%M '), 'description': lorem_ipsum.words(2), 'title': lorem_ipsum.words(2), 'status': Experiment.STATUS[0][0] } self.client.login(username=self.member.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'You have not permission change owners', 1) self.assertEqual(list(Experiment.objects.all().first().owners.all()), [self.owner])
def setUp(self): self.owner = UserFactory() self.member = UserFactory() self.guest = UserFactory() self.user4 = UserFactory() data = { 'name': lorem_ipsum.words(1, False), 'investigator': [self.owner.pk], 'members': [self.member.pk], } self.lab = LabFactory(**data)
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_fake_data(): # create some fake data to make sure we need to paginate if Country.objects.all().count() < 50: for country in COUNTRIES.splitlines(): name, population = country.split(";") Country.objects.create(name=name, visits=0, population=int(population)) if Person.objects.all().count() < 500: countries = list(Country.objects.all()) + [None] Person.objects.bulk_create( [Person(name=words(3, common=False), country=choice(countries)) for i in range(50)] )
def render(self, context): try: count = int(self.count.resolve(context)) except (ValueError, TypeError): count = 1 if self.method == "w": return words(count, common=self.common) else: paras = paragraphs(count, common=self.common) if self.method == "p": paras = ["<p>%s</p>" % p for p in paras] return "\n\n".join(paras)
def test_recent_experiment_activity_view(self): experiment = ExperimentFactory(lab=self.lab, owners=[self.owner.pk], editors=[self.guest.pk]) experiment2 = ExperimentFactory(lab=self.lab, owners=[self.owner.pk], editors=[self.guest.pk]) url = reverse('dashboard:experiment-all-activity', kwargs={'lab_pk': self.lab.pk, 'experiment_pk': experiment.pk}) resp = self.client.get(url) self.assertNotEqual(resp.status_code, 200) self.client.login(username=self.owner.email, password='******') resp = self.client.get(url) self.assertContains(resp, u'timeline') #Update experiment exp_url = reverse('experiments:update', kwargs={'lab_pk': self.lab.pk, 'pk': experiment.pk}) data = { 'owners': [self.owner.pk], 'start': experiment.start.strftime('%m/%d/%Y %H:%M'), 'end': experiment.end.strftime('%m/%d/%Y %H:%M'), 'description': lorem_ipsum.words(2), 'title': experiment.title, 'status': experiment.status } resp = self.client.post(exp_url, data, follow=True) resp = self.client.get(url) self.assertContains(resp, title(self.owner.full_name)) self.assertContains(resp, experiment.title) #Update experiment2 exp_url = reverse('experiments:update', kwargs={'lab_pk': self.lab.pk, 'pk': experiment2.pk}) data = { 'owners': [self.owner.pk], 'start': experiment.start.strftime('%m/%d/%Y %H:%M'), 'end': experiment.end.strftime('%m/%d/%Y %H:%M'), 'description': lorem_ipsum.words(2), 'title': experiment2.title, 'status': experiment.status } resp = self.client.post(exp_url, data, follow=True) resp = self.client.get(url) self.assertNotContains(resp, experiment2.title)
def test_update(self): experiment1 = ExperimentFactory(lab=self.lab, owners=[self.member.pk]) unit1 = UnitFactory(lab=self.lab, user=self.owner, experiments=[experiment1]) collection = CollectionFactory(lab=self.lab, user=self.member, owners=[self.member], units=[unit1]) url = reverse('collections:update', kwargs={'lab_pk': self.lab.pk, 'pk': collection.pk}) data = { 'title': lorem_ipsum.words(3, False), 'units': [unicode(unit.pk) for unit in collection.units], 'owners': [self.owner.pk], } resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertContains(resp, _('Login')) self.client.login(username=self.owner.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertEqual(Collection.objects.first().title, data['title']) self.assertEqual(Collection.objects.count(), 1) data['title'] = lorem_ipsum.words(3, False) self.client.login(username=self.member.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertEqual(Collection.objects.first().title, data['title']) self.assertEqual(Collection.objects.count(), 1) data['title'] = lorem_ipsum.words(3, False) self.client.login(username=self.guest.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertContains(resp, _(u'Select a valid choice. {} is not one of the available choices.'.format(unit1.pk)), 1) self.assertEqual(Collection.objects.count(), 1) self.client.login(username=self.user4.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 403) self.assertEqual(Collection.objects.count(), 1)
def test_recent_experiment_activity_view(self): experiment = ExperimentFactory(lab=self.lab, owners=[self.owner.pk], editors=[self.guest.pk]) experiment2 = ExperimentFactory(lab=self.lab, owners=[self.owner.pk], editors=[self.guest.pk]) url = reverse("dashboard:api-experiment-all", kwargs={"lab_pk": self.lab.pk, "experiment_pk": experiment.pk}) resp = self.client.get(url) self.assertNotEqual(resp.status_code, 200) self.client.login(username=self.owner.email, password="******") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) # Update experiment exp_url = reverse("experiments:update", kwargs={"lab_pk": self.lab.pk, "pk": experiment.pk}) data = { "owners": [self.owner.pk], "start": experiment.start.strftime("%m/%d/%Y %H:%M"), "end": experiment.end.strftime("%m/%d/%Y %H:%M"), "description": lorem_ipsum.words(2), "title": experiment.title, "status": experiment.status, } resp = self.client.post(exp_url, data, follow=True) resp = self.client.get(url) self.assertContains(resp, self.owner.full_name) self.assertContains(resp, experiment.title) # Update experiment2 exp_url = reverse("experiments:update", kwargs={"lab_pk": self.lab.pk, "pk": experiment2.pk}) data = { "owners": [self.owner.pk], "start": experiment.start.strftime("%m/%d/%Y %H:%M"), "end": experiment.end.strftime("%m/%d/%Y %H:%M"), "description": lorem_ipsum.words(2), "title": experiment2.title, "status": experiment.status, } resp = self.client.post(exp_url, data, follow=True) resp = self.client.get(url) self.assertNotContains(resp, experiment2.title)
def test_recent_all_activity_view(self): experiment = ExperimentFactory(lab=self.lab, owners=[self.owner.pk], editors=[self.guest.pk]) url = reverse("dashboard:api-all", kwargs={"lab_pk": self.lab.pk}) resp = self.client.get(url) self.assertNotEqual(resp.status_code, 200) self.client.login(username=self.owner.email, password="******") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) # Update experiment exp_url = reverse("experiments:update", kwargs={"lab_pk": self.lab.pk, "pk": experiment.pk}) data = { "owners": [self.owner.pk], "start": experiment.start.strftime("%m/%d/%Y %H:%M"), "end": experiment.end.strftime("%m/%d/%Y %H:%M"), "description": lorem_ipsum.words(2), "title": experiment.title, "status": experiment.status, } resp = self.client.post(exp_url, data, follow=True) resp = self.client.get(url) self.assertContains(resp, self.owner.full_name) self.assertContains(resp, experiment.title) # Add comment text = lorem_ipsum.words(2) comment_url = reverse( "comment:api-list", kwargs={"lab_pk": self.lab.pk, "instance_type": "experiment", "object_id": experiment.pk}, ) data = {"text": text, "instance_type": "experiment", "object_id": experiment.pk} resp = self.client.post(comment_url, data, format="json") self.assertEqual(resp.status_code, 201) resp = self.client.get(url) self.assertContains(resp, self.owner.full_name) self.assertContains(resp, text)
def create(self, tr): self.tds = tr.find_elements_by_tag_name('td') actions = ActionChains(self.driver) actions.move_to_element(self.tds[1]) actions.double_click() actions.send_keys(lorem_ipsum.words(1, False)) actions.perform() actions.move_to_element(self.tds[2]) actions.double_click() actions.perform() self.driver.select('select.htSelectEditor', unicode(self.experiment.pk)) self.driver.click('body')
def bootstrap(request): '''Demonstrate the use of the bootstrap template''' # create some fake data to make sure we need to paginate if Person.objects.all().count() < 50: countries = list(Country.objects.all()) + [None] Person.objects.bulk_create([ Person(name=words(3, common=False), country=choice(countries)) for i in range(50) ]) table = BootstrapTable(Person.objects.all()) RequestConfig(request, paginate={"per_page": 10}).configure(table) return render(request, 'bootstrap_template.html', { 'table': table })
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_create_lab(self): url = reverse('labs:create') name = lorem_ipsum.words(1, False) data = { 'name': name, 'investigator': [self.owner.pk], 'members': [self.member.pk], } resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertContains(resp, _('Login')) self.client.login(username=self.owner.email, password='******') resp = self.client.post(url, data, follow=True) self.assertEqual(resp.status_code, 200) self.assertEqual(Lab.objects.count(), 1) self.assertEqual(Lab.objects.all().first().name, name)