def test_exclude_entities(self): """ Excluded entities shouldn't returned by get_entities. """ response = self.client.post('/get-entities/', { 'project': self.resource.project.slug, 'locale': self.locale.code, 'paths[]': [self.resource.path], 'excludeEntities[]': [self.entities[1].pk], 'limit': 1, }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') assert_code(response, 200) assert_equal(response.json()['has_next'], True) assert_equal([e['pk'] for e in response.json()['entities']], [self.entities[0].pk,]) response = self.client.post('/get-entities/', { 'project': self.resource.project.slug, 'locale': self.locale.code, 'paths[]': [self.resource.path], 'excludeEntities[]': [self.entities[0].pk, self.entities[1].pk], 'limit': 1, }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') assert_code(response, 200) assert_equal(response.json()['has_next'], False) assert_equal([e['pk'] for e in response.json()['entities']], [self.entities[2].pk])
def test_homepage(self): response = self.client.get('/') data = json.loads(response.content) nt.assert_in('hello', data) nt.assert_equal('world', data['hello']) # new shit only in django-nose nt.assert_code(response, 200)
def test_login_required(self): order = SupplierOrder.objects.create( supplier=self.gladfields, status=SupplierOrder.STATUS_ORDERED) response = self.client.get(reverse('supplier_order_summary_csv', args=(order.id,))) assert_code(response, FOUND) self.assertIn('login', response['Location'])
def test_exclude_entities(self): """ Excluded entities shouldn't returned by get_entities. """ response = self.client.ajax_post('/get-entities/', { 'project': self.resource.project.slug, 'locale': self.locale.code, 'paths[]': [self.resource.path], 'exclude_entities': [self.entities[1].pk], 'limit': 1, }) assert_code(response, 200) assert_equal(response.json()['has_next'], True) assert_equal([e['pk'] for e in response.json()['entities']], [self.entities[0].pk,]) exclude_entities = ','.join(map(str, [ self.entities[0].pk, self.entities[1].pk ])) response = self.client.ajax_post('/get-entities/', { 'project': self.resource.project.slug, 'locale': self.locale.code, 'paths[]': [self.resource.path], 'exclude_entities': exclude_entities, 'limit': 1, }) assert_code(response, 200) assert_equal(response.json()['has_next'], False) assert_equal([e['pk'] for e in response.json()['entities']], [self.entities[2].pk])
def test_user_create_project_view_post_success(self): request = self.rf.post(reverse('project-create'), {'title': 'Test project'}) request.user = self.user response = views.create_project_view(request) assert_code(response, 302) eq_(response['location'], '/projects/') ok_(Project.objects.get(title='Test project'))
def test_timeline_invalid_page(self): """Backend should return 404 error when user requests an invalid/empty page.""" resp = self.client.get('/contributors/{}/timeline/?page=45'.format(self.user.username)) assert_code(resp, 404) resp = self.client.get('/contributors/{}/timeline/?page=-aa45'.format(self.user.username)) assert_code(resp, 404)
def test_bad_unit_size(self): self._login() response = self.app.get(reverse('import_ingredients', args=('Grain',))) with tempfile.TemporaryDirectory() as tempdir: filename = self.create_csv(tempdir, ["Test Grain", 13, "bad unit size", "Gladfields"]) response = self.submit_file_form(filename, response) assert_code(response, FOUND) self.assertIn(reverse('import_ingredients', args=('Grain',)), response['Location']) self.assert_no_ingredient("Test Grain")
def test_user_update_project_view_post_success(self): new_title = 'Changed Title' request = self.rf.post(reverse('project-update', kwargs=self.project_kwargs), {'title': new_title}) request.user = self.user response = views.update_project_view(request, **self.project_kwargs) assert_code(response, 302) eq_(response['location'], reverse('project-list')) project = Project.objects.get(pk=self.test_project.pk) ok_(project.title == new_title)
def test_user_update_ticket_view_post_success(self): request = self.rf.post(reverse('ticket-update', kwargs=self.ticket_kwargs), self.form_post_data) request.user = self.user response = views.update_ticket_view(request, **self.ticket_kwargs) assert_code(response, 302) eq_(response['location'], reverse('project-detail', kwargs=self.project_kwargs)) ticket = Ticket.objects.get(pk=self.test_ticket.pk) ok_(ticket.title == self.form_post_data.get('title')) ok_(request.user in ticket.assignees.all())
def test_hops_created(self): self._login() for name, cost, size, supplier_name in (('Saaz', '12', '100g', 'NZ Hops'), ('Test Hop', '23', 'Kg', 'NZ Hops')): response = self.app.get(reverse('import_ingredients', args=('Hop',))) with tempfile.TemporaryDirectory() as tempdir: filename = self.create_csv(tempdir, [name, cost, size, supplier_name]) response = self.submit_file_form(filename, response) assert_code(response, FOUND) self.assertIn(reverse('import_ingredients', args=('Hop',)), response['Location']) self.assert_hop(name, float(cost), size, supplier_name)
def test_user_update_state_post(self): request = self.rf.post(reverse('ticket-update', kwargs=self.ticket_kwargs), {'transition': 'open'}) request.user = self.user # https://stackoverflow.com/questions/15852317/you-cannot-add-messages-without-installing-django-contrib-messages-middleware-me setattr(request, 'session', 'session') messages = FallbackStorage(request) setattr(request, '_messages', messages) response = views.update_state_ticket_view(request, **self.ticket_kwargs) assert_code(response, 302) ticket = Ticket.objects.get(pk=self.test_ticket.pk) eq_(ticket.state, TICKET_STATES.OPEN)
def test_unapprove_translation(self): """Check if unapprove view works properly.""" response = self.client.ajax_post('/unapprove-translation/', { 'translation': self.translation.pk, 'paths': [], }) assert_code(response, 200) self.translation.refresh_from_db() assert_equal(self.translation.approved, False) assert_equal(self.translation.unapproved_user, self.user)
def test_exclude_entity(self): """ Exclude entity from results to avoid false positive results. """ memory_entry = TranslationMemoryFactory.create(source="Pontoon Intro") response = self.client.get('/translation-memory/', { 'text': 'Pontoon Intro', 'pk': memory_entry.entity.pk, 'locale': memory_entry.locale.code }) assert_code(response, 200) assert_equal(response.content, '[]')
def test_minimal_quality(self): """ View shouldn't return any entries if 70% of quality at minimum. """ # Generate some random entries that shouldn't be similar TranslationMemoryFactory.create_batch(5) response = self.client.get('/translation-memory/', { 'text': 'no match', 'pk': 2, 'locale': 'en-GB' }) assert_code(response, 200) assert_equal(response.content, '[]')
def test_minimal_quality(self): """ View shouldn't return any entries if 70% of quality at minimum. """ # Generate some random entries that shouldn't be similar TranslationMemoryFactory.create_batch(5) response = self.client.get('/translation-memory/', { 'text': 'no match', 'pk': 2, 'locale': 'en-GB' }) assert_code(response, 200) assert_equal(response.content, 'no')
def test_unapprove_translation(self): """Check if unapprove view works properly.""" translation = TranslationFactory.create() translation.approved = True translation.save() response = self.client.ajax_post('/unapprove-translation/', { 'translation': translation.pk, 'paths': [], }) assert_code(response, 200) translation.refresh_from_db() assert_equal(translation.approved, False) assert_equal(translation.unapproved_user, self.user)
def test_manage_project_strings_new_all_empty(self): """Test that sending empty data doesn't create empty strings in the database. """ project = ProjectFactory.create(data_source='database', repositories=[]) url = reverse('pontoon.admin.project.strings', args=(project.slug, )) # Test sending a well-formatted batch of strings. new_strings = " \n \n\n" response = self.client.post(url, {'new_strings': new_strings}) assert_code(response, 200) # Verify no strings have been created as entities. entities = list(Entity.objects.filter(resource__project=project)) assert_equal(len(entities), 0)
def test_inplace_mode(self): """ Inplace mode of get_entites, should return all entities in a single batch. """ response = self.client.ajax_post('/get-entities/', { 'project': self.resource.project.slug, 'locale': self.locale.code, 'paths[]': [self.resource.path], 'inplace_editor': True, # Inplace mode shouldn't respect paging or limiting page 'limit': 1, }) assert_code(response, 200) assert_equal(response.json()['has_next'], False) assert_equal([e['pk'] for e in response.json()['entities']], self.entities_pks)
def post_translation(self, translation, **params): """ Post translation with given params. Returns the last translation object. """ update_params = { 'locale': self.translation.locale.code, 'entity': self.translation.entity.pk, 'translation': translation, 'plural_form': '-1', 'ignore_check': 'true', 'original': self.translation.entity.string, } update_params.update(params) response = self.client.ajax_post('/update/', update_params) assert_code(response, 200) return Translation.objects.last()
def test_exclude_entities(self): """ Excluded entities shouldn't returned by get_entities. """ response = self.client.ajax_post( '/get-entities/', { 'project': self.resource.project.slug, 'locale': self.locale.code, 'paths[]': [self.resource.path], 'exclude_entities': [self.entities[1].pk], 'limit': 1, }) assert_code(response, 200) assert_equal(response.json()['has_next'], True) assert_equal([e['pk'] for e in response.json()['entities']], [ self.entities[0].pk, ]) exclude_entities = ','.join( map(str, [self.entities[0].pk, self.entities[1].pk])) response = self.client.ajax_post( '/get-entities/', { 'project': self.resource.project.slug, 'locale': self.locale.code, 'paths[]': [self.resource.path], 'exclude_entities': exclude_entities, 'limit': 1, }) assert_code(response, 200) assert_equal(response.json()['has_next'], False) assert_equal([e['pk'] for e in response.json()['entities']], [self.entities[2].pk])
def test_exclude_entities(self): """ Excluded entities shouldn't returned by get_entities. """ response = self.client.post('/get-entities/', { 'project': self.resource.project.slug, 'locale': self.locale.code, 'paths[]': [self.resource.path], 'excludeEntities[]': [self.entities[1].pk], 'limit': 1, }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') assert_code(response, 200) assert_equal(response.json()['has_next'], True) assert_equal([e['pk'] for e in response.json()['entities']], [ self.entities[0].pk, ]) response = self.client.post( '/get-entities/', { 'project': self.resource.project.slug, 'locale': self.locale.code, 'paths[]': [self.resource.path], 'excludeEntities[]': [self.entities[0].pk, self.entities[1].pk], 'limit': 1, }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') assert_code(response, 200) assert_equal(response.json()['has_next'], False) assert_equal([e['pk'] for e in response.json()['entities']], [self.entities[2].pk])
def test_manage_project_strings_new(self): project = ProjectFactory.create(data_source='database', repositories=[]) url = reverse('pontoon.admin.project.strings', args=(project.slug, )) # Test sending a well-formatted batch of strings. new_strings = """Hey, I just met you And this is crazy But here's my number So call me maybe? """ response = self.client.post(url, {'new_strings': new_strings}) assert_code(response, 200) # Verify a resource has been created. resources = list(Resource.objects.filter(project=project)) assert_equal(len(resources), 1) assert_equal(resources[0].path, 'database') # Verify all strings have been created as entities. entities = list(Entity.objects.filter(resource__project=project)) assert_equal(len(entities), 4) expected_strings = [ 'Hey, I just met you', 'And this is crazy', 'But here\'s my number', 'So call me maybe?', ] assert_equal(sorted(expected_strings), sorted(x.string for x in entities)) # Verify new strings appear on the page. assert_contains(response, 'Hey, I just met you')
def test_timestamp_invalido(): """Tem de retornar 401 para todos os testes, pois o timestamp está acima da janela permitida""" assert_code( get(funcionarios + '?public_key=1×tamp=' + TIMESTAMP_ANTIGO, hashing=True), 401) assert_code( get(patroes + '?public_key=1×tamp=' + TIMESTAMP_ANTIGO, hashing=True), 401) assert_code( get(usuarios + '?public_key=1×tamp=' + TIMESTAMP_ANTIGO, hashing=True), 401)
def test_GET_valido(): """Tem de retornar 200 para todos os testes, pois a URL é completamente valida""" assert_code( get(funcionarios + '?public_key=1×tamp=' + TIMESTAMP_AGORA, hashing=True), 200) assert_code( get(patroes + '?public_key=1×tamp=' + TIMESTAMP_AGORA, hashing=True), 200) assert_code( get(usuarios + '?public_key=1×tamp=' + TIMESTAMP_AGORA, hashing=True), 200)
def test_manage_project_strings(self): project = ProjectFactory.create(data_source='database', repositories=[]) url = reverse('pontoon.admin.project.strings', args=(project.slug, )) # Test with anonymous user. response = self.client.get(url) assert_code(response, 403) # Test with a user that is not a superuser. user = UserFactory.create() self.client.force_login(user) response = self.client.get(url) assert_code(response, 403) # Test with a superuser. user.is_superuser = True user.save() response = self.client.get(url) assert_code(response, 200)
def test_user_create_ticket_get(self): request = self.rf.get(reverse('ticket-create', kwargs=self.project_kwargs)) request.user = self.user response = views.create_ticket_view(request, **self.project_kwargs) assert_code(response, 200) ok_(response.render())
def test_locale_file_download(self): """By download the data.""" response = self.get_tmx_file(self.locale.code, self.project.slug) assert_code(response, 200) assert_xml(''.join(response.streaming_content).encode('utf-8'))
def test_api_key_nao_encontrado(): """Tem de retornar 401 para todos os testes, pois não existe a api_key na url""" assert_code(get(funcionarios + '?public_key=1', hashing=False), 401) assert_code(get(patroes + '?public_key=1', hashing=False), 401) assert_code(get(usuarios + '?public_key=1', hashing=False), 401)
def test_invalid_parameters(self): """Validate locale code and don't return data.""" assert_code(self.get_tmx_file('invalidlocale', 'invalidproject'), 404) assert_code(self.get_tmx_file(self.locale.code, 'invalidproject'), 404)
def test_public_key_invalido(): """Tem de retornar 401 para todos os testes, pois a public_key é inválido""" assert_code(get(funcionarios + '?public_key=20'), 401) assert_code(get(patroes + '?public_key=20'), 401) assert_code(get(usuarios + '?public_key=20'), 401)
def test_locale_doesnt_exist(self): """ Tests if view is returning an error on the missing locale. """ assert_code(self.client.get('/missing-locale/contributors/'), 404)
def test_vote_simple_view(self): self.client.login(username=self.user.username, password=self.USER_PASSWORD) assert_code(self.client.get(self.url), 200)
def test_manage_project_strings_bad_request(self): # Tets an unknown project returns a 404 error. url = reverse('pontoon.admin.project.strings', args=('unknown', )) response = self.client.get(url) assert_code(response, 404)
def test_manage_project(self): url = reverse('pontoon.admin.project.new') response = self.client.get(url) assert_code(response, 200)
def test_manage_project_strings_download_csv(self): locale_kl = LocaleFactory.create(code='kl', name='Klingon') locale_gs = LocaleFactory.create(code='gs', name='Geonosian') project = ProjectFactory.create(data_source='database', locales=[locale_kl, locale_gs], repositories=[]) url = reverse('pontoon.admin.project.strings', args=(project.slug, )) new_strings = """ And on the pedestal these words appear: 'My name is Ozymandias, king of kings: Look on my works, ye Mighty, and despair!' """ response = self.client.post(url, {'new_strings': new_strings}) assert_code(response, 200) # Test downloading the data. response = self.client.get(url, {'format': 'csv'}) assert_code(response, 200) assert_equal(response._headers['content-type'], ('Content-Type', 'text/csv')) # Verify the original content is here. assert_contains(response, 'pedestal') assert_contains(response, 'Ozymandias') assert_contains(response, 'Mighty') # Verify we have the locale columns. assert_contains(response, 'kl') assert_contains(response, 'gs') # Now add some translations. entity = Entity.objects.filter( string='And on the pedestal these words appear:')[0] Translation( string='Et sur le piédestal il y a ces mots :', entity=entity, locale=locale_kl, approved=True, ).save() Translation( string='Und auf dem Sockel steht die Schrift: ‚Mein Name', entity=entity, locale=locale_gs, approved=True, ).save() entity = Entity.objects.filter( string='\'My name is Ozymandias, king of kings:')[0] Translation( string='"Mon nom est Ozymandias, Roi des Rois.', entity=entity, locale=locale_kl, approved=True, ).save() Translation( string='Ist Osymandias, aller Kön’ge König: –', entity=entity, locale=locale_gs, approved=True, ).save() entity = Entity.objects.filter( string='Look on my works, ye Mighty, and despair!\'')[0] Translation( string='Voyez mon œuvre, vous puissants, et désespérez !"', entity=entity, locale=locale_kl, approved=True, ).save() Translation( string='Seht meine Werke, Mächt’ge, und erbebt!‘', entity=entity, locale=locale_gs, approved=True, ).save() response = self.client.get(url, {'format': 'csv'}) # Verify the translated content is here. assert_contains(response, 'pedestal') assert_contains(response, 'piédestal') assert_contains(response, 'Sockel') assert_contains(response, 'Mighty') assert_contains(response, 'puissants') assert_contains(response, 'Mächt’ge')
def test_manage_project_strings_list(self): project = ProjectFactory.create(data_source='database', repositories=[]) resource = ResourceFactory.create(project=project) nb_entities = 2 entities = EntityFactory.create_batch(nb_entities, resource=resource) url = reverse('pontoon.admin.project.strings', args=(project.slug, )) response = self.client.get(url) assert_code(response, 200) for i in range(nb_entities): assert_contains(response, 'string %s' % i) # Test editing strings and comments. form_data = { 'form-TOTAL_FORMS': nb_entities, 'form-INITIAL_FORMS': nb_entities, 'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1000, 'form-0-id': entities[0].id, 'form-0-string': 'changed 0', 'form-0-comment': 'Wubba lubba dub dub', 'form-1-id': entities[1].id, 'form-1-string': 'string 1', 'form-1-obsolete': 'on', # Remove this one. } response = self.client.post(url, form_data) assert_code(response, 200) assert_contains(response, 'changed 0') assert_contains(response, 'Wubba lubba dub dub') assert_not_contains(response, 'string 0') assert_not_contains(response, 'string 1') # It's been removed. total = Entity.objects.filter( resource=resource, obsolete=False, ).count() assert_equal(total, nb_entities - 1) # Test adding a new string. form_data = { 'form-TOTAL_FORMS': nb_entities, 'form-INITIAL_FORMS': nb_entities - 1, 'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1000, 'form-0-id': entities[0].id, 'form-0-string': 'changed 0', 'form-0-comment': 'Wubba lubba dub dub', 'form-1-id': '', 'form-1-string': 'new string', 'form-1-comment': 'adding this entity now', } response = self.client.post(url, form_data) assert_code(response, 200) assert_contains(response, 'changed 0') assert_contains(response, 'new string') assert_contains(response, 'adding this entity now') total = Entity.objects.filter( resource=resource, obsolete=False, ).count() assert_equal(total, nb_entities)
def test_DELETE_patrao(): """Tem de retornar o codigo 204, pois informará que o patrao foi excluído""" response = delete(patroes + '1/' + '?public_key=2×tamp=' + TIMESTAMP_AGORA) assert_code(response, 204)
def test_poll_details_ok(self): poll = self.get_polls()[0] url = reverse("poll:detail", kwargs={"pk": poll.pk}) assert_code(self.client.get(url), 200)
def test_vote_requires_login(self): assert_code(self.client.get(self.url), 302)
def test_POST_patrao(): """Tem de retornar o codigo 201, informando que o patrao foi cadastrado""" response = post(patroes + '?public_key=2×tamp=' + TIMESTAMP_AGORA, {"usuario": "/api/v1/usuario/2/"}) assert_code(response, 201)
def test_vote_inactive_poll_redirect(self): self.client.login(username=self.user.username, password=self.USER_PASSWORD) self.poll.start = factories.YEYESTERDAY self.poll.end = factories.YESTERDAY self.poll.save() assert_code(self.client.get(self.url), 302)
def test_project_doesnt_exist(self): """ Checks if view is returning error when project slug is invalid. """ assert_code(self.client.get('/projects/project_doesnt_exist/'), 404)
def test_DELETE_usuario(): """Tem de retornar o codigo 204, pois informará que o usuário foi excluído""" response = delete(usuarios + '1/' + '?public_key=1×tamp=' + TIMESTAMP_AGORA) assert_code(response, 204)
def test_project_doesnt_exist(self): """ Checks if view handles invalid project. """ assert_code(self.client.get('/projects/project_doesnt_exist/contributors/'), 404)
def test_simple_view(self): assert_code(self.client.get(self.url), 200)
def test_timestamp_nao_encontrado(): """Tem de retornar 401 para todos os testes, pois não existe o timestamp na url""" assert_code(get(funcionarios + '?public_key=1', hashing=True), 401) assert_code(get(patroes + '?public_key=1', hashing=True), 401) assert_code(get(usuarios + '?public_key=1', hashing=True), 401)
def check_200_resp(self, url): assert_code(self.client.get(url), 200)
def test_public_key_nao_encontrado(): """Tem de retornar 401 para todos os testes, pois não existe a public_key na url""" assert_code(get(funcionarios), 401) assert_code(get(patroes), 401) assert_code(get(usuarios), 401)
def test_poll_list_ok(self): url = reverse("poll:list") self.get_polls() assert_code(self.client.get(url), 200)