def test_is_feature_enabled(self): request = RequestFactory().get('/') request.user = AnonymousUser() # Return True if no switch or flag are provided self.assertTrue(utils.is_feature_enabled({'switch': None, 'flag': None}, request)) name = 'test-waffle' item = {'switch': 'test-waffle'} # Return False if switch inactive with override_switch(name, active=False): self.assertFalse(utils.is_feature_enabled(item, request)) # Return True if switch active with override_switch(name, active=True): self.assertTrue(utils.is_feature_enabled(item, request)) item = {'flag': 'test-waffle'} # Return False if flag inactive with override_flag(name, active=False): self.assertFalse(utils.is_feature_enabled(item, request)) # Return True if flag active with override_flag(name, active=True): self.assertTrue(utils.is_feature_enabled(item, request))
def test_summary_min_length(self): delicious = Addon.objects.get() assert delicious.type == amo.ADDON_EXTENSION with override_switch('content-optimization', active=False): form = forms.DescribeForm( {'name': 'Delicious for everyone', 'summary': 'foo', 'slug': 'bar', 'description': '123456789'}, request=self.request, instance=delicious) assert form.is_valid(), form.errors with override_switch('content-optimization', active=True): form = forms.DescribeForm( {'name': 'Delicious for everyone', 'summary': 'foo', 'slug': 'bar', 'description': '123456789'}, request=self.request, instance=delicious) assert not form.is_valid() # But only extensions have a minimum length delicious.update(type=amo.ADDON_STATICTHEME) form = forms.DescribeForm( {'name': 'Delicious for everyone', 'summary': 'foo', 'slug': 'bar', 'description': '123456789'}, request=self.request, instance=delicious) assert form.is_valid() # Do it again, but this time with a description delicious.update(type=amo.ADDON_EXTENSION) form = forms.DescribeForm( {'name': 'Delicious for everyone', 'summary': 'foo', 'slug': 'bar', 'description': '1234567890'}, request=self.request, instance=delicious) assert form.is_valid(), form.errors
def test_description_optional(self): delicious = Addon.objects.get() assert delicious.type == amo.ADDON_EXTENSION with override_switch('content-optimization', active=False): form = forms.DescribeForm( {'name': u'Delicious for everyone', 'summary': u'foo', 'slug': u'bar'}, request=self.request, instance=delicious) assert form.is_valid(), form.errors with override_switch('content-optimization', active=True): form = forms.DescribeForm( {'name': u'Delicious for everyone', 'summary': u'foo', 'slug': u'bar'}, request=self.request, instance=delicious) assert not form.is_valid() # But only extensions are required to have a description delicious.update(type=amo.ADDON_STATICTHEME) form = forms.DescribeForm( {'name': u'Delicious for everyone', 'summary': u'foo', 'slug': u'bar'}, request=self.request, instance=delicious) assert form.is_valid(), form.errors # Do it again, but this time with a description delicious.update(type=amo.ADDON_EXTENSION) form = forms.DescribeForm( {'name': u'Delicious for everyone', 'summary': u'foo', 'slug': u'bar', 'description': u'its a description'}, request=self.request, instance=delicious) assert form.is_valid(), form.errors
def test_new_switch(self): assert not Switch.objects.filter(name='foo').exists() with override_switch('foo', active=True): assert waffle.switch_is_active('foo') with override_switch('foo', active=False): assert not waffle.switch_is_active('foo') assert not Switch.objects.filter(name='foo').exists()
def test_new_switch(self): assert not Switch.objects.filter(name="foo").exists() with override_switch("foo", active=True): assert waffle.switch_is_active(req(), "foo") with override_switch("foo", active=False): assert not waffle.switch_is_active(req(), "foo") assert not Switch.objects.filter(name="foo").exists()
def test_cache_is_flushed_by_testutils_even_in_transaction(self): Switch.objects.create(name='foo', active=True) with transaction.atomic(): with override_switch('foo', active=True): assert waffle.switch_is_active('foo') with override_switch('foo', active=False): assert not waffle.switch_is_active('foo') assert waffle.switch_is_active('foo')
def test_switch_existed_and_was_NOT_active(self): Switch.objects.create(name='foo', active=False) with override_switch('foo', active=True): assert waffle.switch_is_active('foo') with override_switch('foo', active=False): assert not waffle.switch_is_active('foo') # make sure it didn't change 'active' value assert not Switch.objects.get(name='foo').active
def test_switch_existed_and_was_active(self): Switch.objects.create(name="foo", active=True) with override_switch("foo", active=True): assert waffle.switch_is_active(req(), "foo") with override_switch("foo", active=False): assert not waffle.switch_is_active(req(), "foo") # make sure it didn't change 'active' value assert Switch.objects.get(name="foo").active
def test_check_akismet_reports(return_value, headers, waffle_on, flag_count): task_user = user_factory(id=settings.TASK_USER_ID) assert RatingFlag.objects.count() == 0 rating = Rating.objects.create( addon=addon_factory(), user=user_factory(), rating=4, body=u'spám?', ip_address='1.2.3.4') akismet_report = AkismetReport.create_for_rating(rating, 'foo/baa', '') with mock.patch('olympia.lib.akismet.models.requests.post') as post_mock: # Mock a definitely spam response - same outcome post_mock.return_value.json.return_value = return_value post_mock.return_value.headers = headers with override_switch('akismet-rating-action', active=waffle_on): check_akismet_reports([akismet_report.id]) RatingFlag.objects.count() == flag_count rating = rating.reload() if flag_count > 0: flag = RatingFlag.objects.get() assert flag.rating == rating assert flag.user == task_user assert flag.flag == RatingFlag.SPAM assert rating.editorreview else: assert not rating.editorreview
def test_code_sample(code_sample_doc, client, settings, domain): """The raw source for a document can be requested.""" url = reverse('wiki.code_sample', args=[code_sample_doc.slug, 'sample1']) setattr(settings, 'ATTACHMENT_' + domain, 'testserver') with override_switch('application_ACAO', True): response = client.get(url, HTTP_HOST='testserver', HTTP_IF_NONE_MATCH='"some-old-etag"') assert response.status_code == 200 assert response['Access-Control-Allow-Origin'] == '*' assert 'Last-Modified' not in response assert 'ETag' in response assert 'public' in response['Cache-Control'] assert 'max-age=86400' in response['Cache-Control'] assert response.content.startswith(b'<!DOCTYPE html>') normalized = normalize_html(response.content) expected = ('<meta charset="utf-8">' '<link href="%sbuild/styles/samples.css"' ' rel="stylesheet" type="text/css">' '<style type="text/css">.some-css { color: red; }</style>' '<title>Root Document - sample1 - code sample</title>' 'Some HTML' '<script>window.alert("HI THERE")</script>' % settings.STATIC_URL) assert normalized == expected
def test_try_new_frontend_banner_presence(self): response = self.client.get(self.url) assert 'AMO is getting a new look.' not in response.content with override_switch('try-new-frontend', active=True): response = self.client.get(self.url) assert 'AMO is getting a new look.' in response.content
def test_has_project_and_draft_registration(self): prereg_schema = RegistrationSchema.objects.get(name='Prereg Challenge') factories.DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema ) assert_equal( landing_page(user=self.user), { 'has_projects': True, 'has_draft_registrations': True, 'campaign_long': 'Prereg Challenge', 'campaign_short': 'prereg_challenge', 'is_logged_in': True, } ) with override_switch(name=OSF_PREREGISTRATION, active=True): prereg_schema = RegistrationSchema.objects.get(name='OSF Preregistration') factories.DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema ) assert_equal( landing_page(user=self.user), { 'has_projects': True, 'has_draft_registrations': True, 'campaign_long': 'OSF Preregistration', 'campaign_short': 'prereg', 'is_logged_in': True, } )
def test_translate_template(client): url = reverse('pontoon.translate.next') with override_switch('translate_next', active=True): response = client.get(url) assert response.status_code == 200 assert 'Translate.Next' in response.content
def test_has_project(self): factories.ProjectFactory(creator=self.user) assert_equal( landing_page(user=self.user), { 'has_projects': True, 'has_draft_registrations': False, 'campaign_long': 'Prereg Challenge', 'campaign_short': 'prereg_challenge', 'is_logged_in': True, } ) with override_switch(name=OSF_PREREGISTRATION, active=True): assert_equal( landing_page(user=self.user), { 'has_projects': True, 'has_draft_registrations': False, 'campaign_long': 'OSF Preregistration', 'campaign_short': 'prereg', 'is_logged_in': True, } )
def test_maybe_check_with_akismet(body, pre_save_body, user_id, user_id_resp, waffle_enabled, is_checked): user = user_factory( id=user_id, username='******' % user_id, email='%s@e' % user_id) rating_kw = { 'addon': addon_factory(), 'user': user, 'rating': 4, 'body': body, 'ip_address': '1.2.3.4'} if user_id_resp: rating_kw['user_responsible'] = ( user if user_id_resp == user_id else user_factory( id=user_id_resp, username='******' % user_id_resp, email='%s@e' % user_id_resp)) rating = Rating.objects.create(**rating_kw) request = RequestFactory().get('/') to_patch = 'olympia.ratings.utils.check_akismet_reports.delay' with mock.patch(to_patch) as check_akismet_reports_mock: with override_switch('akismet-spam-check', active=waffle_enabled): result = maybe_check_with_akismet(request, rating, pre_save_body) assert result == is_checked if is_checked: assert AkismetReport.objects.count() == 1 check_akismet_reports_mock.assert_called() else: assert AkismetReport.objects.count() == 0 check_akismet_reports_mock.assert_not_called()
def test_try_new_frontend_banner_presence(self): response = self.client.get(self.url) assert b'AMO is getting a new look.' not in response.content with override_switch('try-new-frontend', active=True): response = self.client.get(self.url) assert b'AMO is getting a new look.' in response.content
def test_send_csrf_cookie_and_headers(self, app, csrf_token, url, payload): app.set_cookie(CSRF_COOKIE_NAME, csrf_token) with override_switch('enforce_csrf', active=True): res = app.post_json_api(url, payload, headers={'X-CSRFToken': csrf_token}, expect_errors=True) assert res.status_code == 201
def test_disable_populate_daily_metrics(caplog, func): """Test figures.tasks.populate_daily_metrics Tests that when WAFFLE_DISABLE_PIPELINE is active, the disabled warning msg is logged """ with override_switch('figures.disable_pipeline', active=True): func() assert 'disabled' in caplog.text
def test_waffle_switch_inactive_does_not_enforce_csrf(self, app, url, payload): with override_switch('enforce_csrf', active=False): res = app.post_json_api( url, payload, expect_errors=True ) assert res.status_code == 201
def test_date_fields_are_hidden_when_switch_enabled(self, is_switch_enabled): with override_switch(PUBLISHER_ENABLE_READ_ONLY_FIELDS, active=is_switch_enabled): run_form = CourseRunForm( hide_start_date_field=is_switch_enabled, hide_end_date_field=is_switch_enabled ) self.assertEqual(run_form.fields['start'].widget.is_hidden, is_switch_enabled) self.assertEqual(run_form.fields['end'].widget.is_hidden, is_switch_enabled)
def test_enable_populate_daily_metrics(caplog): """Test figures.tasks.populate_daily_metrics Tests that when WAFFLE_DISABLE_PIPELINE is not active, the disabled warning msg is not logged """ with override_switch('figures.disable_pipeline', active=False): populate_daily_metrics() assert 'disabled' not in caplog.text
def test_post_no_csrf_cookie(self, app, url, payload): with override_switch('enforce_csrf', active=True): res = app.post_json_api( url, payload, expect_errors=True ) assert res.status_code == 403 assert csrf.REASON_NO_CSRF_COOKIE in res.json['errors'][0]['detail']
def test_translate_behind_switch(client): url = reverse('pontoon.translate.next') response = client.get(url) assert response.status_code == 404 with override_switch('translate_next', active=True): response = client.get(url) assert response.status_code == 200
def test_prereg_challenge_over(self): url = self.draft_api_url('submit_draft_for_review') with override_switch(features.OSF_PREREGISTRATION, active=True): res = self.app.post_json(url, self.embargo_payload, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, http_status.HTTP_410_GONE) data = res.json assert_equal(data['message_short'], 'The Prereg Challenge has ended')
def test_send_csrf_cookie_and_headers(self, app, csrf_token, url, payload): app.set_cookie(CSRF_COOKIE_NAME, csrf_token) with override_switch('enforce_csrf', active=True): res = app.post_json_api( url, payload, headers={'X-CSRFToken': csrf_token}, expect_errors=True ) assert res.status_code == 201
def test_post_without_csrf_in_headers(self, app, csrf_token, url, payload): app.set_cookie(CSRF_COOKIE_NAME, csrf_token) with override_switch('enforce_csrf', active=True): res = app.post_json_api( url, payload, expect_errors=True ) assert res.status_code == 403 assert csrf.REASON_BAD_TOKEN in res.json['errors'][0]['detail']
def test_add_guid_no_guid(self): file_ = version_factory( addon=self.addon, file_kw={'filename': 'webextension_no_id.xpi'} ).file with open(file_.current_file_path, 'rb') as fobj: contents = fobj.read() # with the waffle off it's the same as with an existing guid with override_switch('add-guid-to-manifest', active=False): assert signing.add_guid(file_) == contents # if it's on though, it's different with override_switch('add-guid-to-manifest', active=True): zip_blob = signing.add_guid(file_) assert zip_blob != contents # compare the zip contents with ( zipfile.ZipFile(file_.current_file_path) as orig_zip, zipfile.ZipFile(io.BytesIO(zip_blob)) as new_zip, ): for info in orig_zip.filelist: if info.filename != 'manifest.json': # all other files should be the same orig_zip.open(info.filename).read() == new_zip.open( info.filename ).read() else: # only manifest.json should have been updated orig_manifest = json.load(orig_zip.open(info.filename)) new_manifest_blob = new_zip.open(info.filename).read() new_manifest = json.loads(new_manifest_blob) assert orig_manifest != new_manifest assert new_manifest['browser_specific_settings']['gecko']['id'] == ( self.file_.addon.guid ) assert orig_manifest == { key: value for key, value in new_manifest.items() if key != 'browser_specific_settings' } # check the manifest is formatted well, with spacing and line breaks assert new_manifest_blob.decode('utf8').startswith('{\n "manifest') assert 'manifest.json' in (info.filename for info in orig_zip.filelist) assert len(orig_zip.filelist) == len(new_zip.filelist)
def test_revisions_show_ips_button(switch, is_admin, root_doc, user_client, admin_client): """Toggle IPs button appears for admins when the switch is active.""" client = admin_client if is_admin else user_client with override_switch('store_revision_ips', active=switch): response = client.get(reverse('dashboards.revisions')) assert response.status_code == 200 page = pq(response.content) ip_button = page.find('button#show_ips_btn') assert len(ip_button) == (1 if (switch and is_admin) else 0)
def test_description_optional(self): delicious = Addon.objects.get() assert delicious.type == amo.ADDON_EXTENSION with override_switch('content-optimization', active=False): form = forms.DescribeForm( {'name': 'Delicious for everyone', 'summary': 'foo', 'slug': 'bar'}, request=self.request, instance=delicious, ) assert form.is_valid(), form.errors with override_switch('content-optimization', active=True): form = forms.DescribeForm( {'name': 'Delicious for everyone', 'summary': 'foo', 'slug': 'bar'}, request=self.request, instance=delicious, ) assert not form.is_valid() # But only extensions are required to have a description delicious.update(type=amo.ADDON_STATICTHEME) form = forms.DescribeForm( {'name': 'Delicious for everyone', 'summary': 'foo', 'slug': 'bar'}, request=self.request, instance=delicious, ) assert form.is_valid(), form.errors # Do it again, but this time with a description delicious.update(type=amo.ADDON_EXTENSION) form = forms.DescribeForm( { 'name': 'Delicious for everyone', 'summary': 'foo', 'slug': 'bar', 'description': 'its a description', }, request=self.request, instance=delicious, ) assert form.is_valid(), form.errors
def test_cache_invalidation(self, invalidate_cache_enabled, mock_bs_manager_clear): test_display_name = "Jedi 101" with override_switch(INVALIDATE_CACHE_ON_PUBLISH_SWITCH, active=invalidate_cache_enabled): self.course.display_name = test_display_name self.store.update_item(self.course, self.user.id) self.assertEquals(mock_bs_manager_clear.called, invalidate_cache_enabled)
def test_verify_mozilla_trademark(name, allowed, email, content_optmzn_waffle): user = user_factory(email=email) with override_switch('content-optimization', active=content_optmzn_waffle): if not allowed: with pytest.raises(ValidationError) as exc: verify_mozilla_trademark(name, user) assert exc.value.message == ( 'Add-on names cannot contain the Mozilla or Firefox ' 'trademarks.') else: verify_mozilla_trademark(name, user)
def test_prereg_challenge_over(self): url = self.draft_api_url('submit_draft_for_review') with override_switch(features.OSF_PREREGISTRATION, active=True): res = self.app.post_json( url, self.embargo_payload, auth=self.user.auth, expect_errors=True ) assert_equal(res.status_code, http.GONE) data = res.json assert_equal(data['message_short'], 'The Prereg Challenge has ended')
def test_schemas_list_crud(self, app): user = AuthUserFactory() url = '/{}schemas/registrations/?version=2.11'.format(API_BASE) schemas = RegistrationSchema.objects.filter( schema_version=LATEST_SCHEMA_VERSION) # test_pass_authenticated_user_can_view_schemas with override_switch(ENABLE_INACTIVE_SCHEMAS, active=False): res = app.get(url, auth=user.auth) assert res.status_code == 200 assert res.json['meta']['total'] == schemas.filter( active=True, visible=True).count() with override_switch(ENABLE_INACTIVE_SCHEMAS, active=True): res = app.get(url, auth=user.auth) assert res.status_code == 200 assert res.json['meta']['total'] == schemas.filter( visible=True).count() # test_cannot_update_metaschemas res = app.put_json_api(url, auth=user.auth, expect_errors=True) assert res.status_code == 405 # test_cannot_post_metaschemas res = app.post_json_api(url, auth=user.auth, expect_errors=True) assert res.status_code == 405 # test_pass_unauthenticated_user_can_view_schemas res = app.get(url) assert res.status_code == 200 # test_filter_on_active url = '/{}schemas/registrations/?version=2.11&filter[active]=True'.format( API_BASE) with override_switch(ENABLE_INACTIVE_SCHEMAS, active=True): res = app.get(url) assert res.status_code == 200 assert res.json['meta']['total'] == schemas.filter(active=True).count()
def test_verify_mozilla_trademark(name, allowed, email, content_optmzn_waffle): user = user_factory(email=email) with override_switch('content-optimization', active=content_optmzn_waffle): if not allowed: with pytest.raises(ValidationError) as exc: verify_mozilla_trademark(name, user) assert exc.value.message == ( 'Add-on names cannot contain the Mozilla or Firefox ' 'trademarks.' ) else: verify_mozilla_trademark(name, user)
def test_auto_import_blocklist_waffle(call_command_mock): with override_switch('blocklist_auto_import', active=False): with mock.patch('django_statsd.clients.statsd.incr') as incr_mock: auto_import_blocklist() incr_mock.assert_not_called() call_command_mock.assert_not_called() with override_switch('blocklist_auto_import', active=True): with mock.patch('django_statsd.clients.statsd.incr') as incr_mock: auto_import_blocklist() incr_mock.assert_called_with( 'blocklist.cron.import_blocklist.success') call_command_mock.assert_called() call_command_mock.side_effect = CommandError('foo') with override_switch('blocklist_auto_import', active=True): with mock.patch('django_statsd.clients.statsd.incr') as incr_mock: try: auto_import_blocklist() except CommandError: pass incr_mock.assert_called_with( 'blocklist.cron.import_blocklist.failure')
def test_has_read_developer_agreement(self): now = self.days_ago(0) recently = self.days_ago(1) older_date = self.days_ago(42) assert not UserProfile().has_read_developer_agreement() assert not UserProfile( read_dev_agreement=None).has_read_developer_agreement() assert UserProfile( read_dev_agreement=older_date).has_read_developer_agreement() with override_switch('post-review', active=True): Switch.objects.filter(name='post-review').update(modified=recently) # Still False. assert not UserProfile().has_read_developer_agreement() # User has read the agreement, before it was modified for # post-review: it should return False. assert not UserProfile( read_dev_agreement=older_date).has_read_developer_agreement() # User has read the agreement after it was modified for # post-review: it should return True. assert UserProfile( read_dev_agreement=now).has_read_developer_agreement() with override_switch('post-review', active=False): Switch.objects.filter(name='post-review').update(modified=recently) # Still False. assert not UserProfile().has_read_developer_agreement() # Both should be True, the date does not matter any more. assert UserProfile( read_dev_agreement=older_date).has_read_developer_agreement() assert UserProfile( read_dev_agreement=now).has_read_developer_agreement()
def test_schemas_list_crud(self, app): user = AuthUserFactory() url = '/{}schemas/registrations/?version=2.11'.format(API_BASE) schemas = RegistrationSchema.objects.filter(schema_version=LATEST_SCHEMA_VERSION) # test_pass_authenticated_user_can_view_schemas with override_switch(ENABLE_INACTIVE_SCHEMAS, active=False): res = app.get(url, auth=user.auth) assert res.status_code == 200 assert res.json['meta']['total'] == schemas.filter(active=True, visible=True).count() with override_switch(ENABLE_INACTIVE_SCHEMAS, active=True): res = app.get(url, auth=user.auth) assert res.status_code == 200 assert res.json['meta']['total'] == schemas.filter(visible=True).count() # test_cannot_update_metaschemas res = app.put_json_api(url, auth=user.auth, expect_errors=True) assert res.status_code == 405 # test_cannot_post_metaschemas res = app.post_json_api(url, auth=user.auth, expect_errors=True) assert res.status_code == 405 # test_pass_unauthenticated_user_can_view_schemas res = app.get(url) assert res.status_code == 200 # test_filter_on_active url = '/{}schemas/registrations/?version=2.11&filter[active]=True'.format(API_BASE) with override_switch(ENABLE_INACTIVE_SCHEMAS, active=True): res = app.get(url) assert res.status_code == 200 assert res.json['meta']['total'] == schemas.filter(active=True).count()
def test_autosuggest(client, redirect_doc, doc_hierarchy, locale_case, term): params = {} expected_status_code = 200 if term: params.update(term=term) else: expected_status_code = 400 if locale_case == "non-english-locale": params.update(locale="it") expected_titles = {"Superiore Documento"} elif locale_case == "current-locale": params.update(current_locale="true") # The root document is pulled-in by the redirect_doc fixture. expected_titles = { "Root Document", "Top Document", "Middle-Top Document", "Middle-Bottom Document", "Bottom Document", } elif locale_case == "exclude-current-locale": params.update(exclude_current_locale="true") expected_titles = {"Haut Document", "Superiore Documento"} else: # All locales # The root document is pulled-in by the redirect_doc fixture. expected_titles = { "Root Document", "Top Document", "Haut Document", "Superiore Documento", "Middle-Top Document", "Middle-Bottom Document", "Bottom Document", } url = reverse("wiki.autosuggest_documents") if params: url += "?{}".format(urlencode(params)) with override_switch("application_ACAO", True): response = client.get(url) assert response.status_code == expected_status_code assert_shared_cache_header(response) assert "Access-Control-Allow-Origin" in response assert response["Access-Control-Allow-Origin"] == "*" if expected_status_code == 200: assert response["Content-Type"] == "application/json" data = json.loads(response.content) assert set(item["title"] for item in data) == expected_titles
def test_is_readonly(self): block = Block.objects.create(guid='foo@baa', updated_by=user_factory()) # not read only by default assert not block.is_readonly # but should be if there's an active BlocklistSubmission block.active_submissions = [object()] # just needs to be non-empty assert block.is_readonly # otherwise legacy_id being non-false means it's imported, so readonly del block.active_submissions assert not block.is_readonly block.legacy_id = 'something' assert block.is_readonly # except when legacy submissions are enabled to keep it in-sync. with override_switch('blocklist_legacy_submit', active=True): assert not block.is_readonly
def test_get_programs_with_type_called(self, multitenant_programs_enabled): views = [ (reverse('root'), 'student.views.get_programs_with_type'), (reverse('branding.views.courses'), 'courseware.views.views.get_programs_with_type'), ] for url, dotted_path in views: with patch(dotted_path) as mock_get_programs_with_type: with override_switch('get-multitenant-programs', multitenant_programs_enabled): response = self.client.get(url) self.assertEqual(response.status_code, 200) if multitenant_programs_enabled: mock_get_programs_with_type.assert_called_once() else: mock_get_programs_with_type.assert_not_called()
def test_addon(self): responses.add( responses.POST, 'https://basket.allizom.org/amo-sync/addon/', json=True ) with override_switch('basket-amo-sync', active=False): # Gotta deactivate the sync when calling addon_factory() because # the change to _current_version inside will trigger a sync. addon = addon_factory() sync_objects_to_basket('addon', [addon.pk]) assert len(responses.calls) == 1 request = responses.calls[0].request assert request.headers['x-api-key'] == settings.BASKET_API_KEY body = request.body data = json.loads(body) expected_data = AddonBasketSyncSerializer(addon).data assert expected_data assert data == expected_data
def test_course_run_comment_email(self, is_switch_enabled): """ Verify that after adding a comment against a course-run emails send to multiple users depending upon the parent course related group. """ with override_switch(PUBLISHER_ENABLE_READ_ONLY_FIELDS, active=is_switch_enabled): comment = self.create_comment(content_object=self.course_run) subject = 'Comment added: {title} {start} - {pacing_type}'.format( title=self.course_run.course.title, pacing_type=self.course_run.get_pacing_type_temporary_display( ), start=self.course_run.start_date_temporary.strftime( '%B %d, %Y')) self.assert_comment_email_sent( self.course_run, comment, reverse('publisher:publisher_course_run_detail', args=[self.course_run.id]), subject)
def test_json(doc_hierarchy, client, params_case): """Test the wiki.json endpoint.""" top_doc = doc_hierarchy.top bottom_doc = doc_hierarchy.bottom expected_tags = sorted(["foo", "bar", "baz"]) expected_review_tags = sorted(["tech", "editorial"]) for doc in (top_doc, bottom_doc): doc.tags.set(*expected_tags) doc.current_revision.review_tags.set(*expected_review_tags) params = None expected_slug = None expected_status_code = 200 if params_case == "nothing": expected_status_code = 400 elif params_case == "title-only": expected_slug = top_doc.slug params = dict(title=top_doc.title) elif params_case == "slug-only": expected_slug = bottom_doc.slug params = dict(slug=bottom_doc.slug) elif params_case == "title-and-slug": expected_slug = top_doc.slug params = dict(title=top_doc.title, slug=bottom_doc.slug) else: # missing title expected_status_code = 404 params = dict(title="nonexistent document title") url = reverse("wiki.json") with override_switch("application_ACAO", True): response = client.get(url, params) assert response.status_code == expected_status_code if response.status_code == 404: assert_no_cache_header(response) else: assert_shared_cache_header(response) assert response["Access-Control-Allow-Origin"] == "*" if response.status_code == 200: data = json.loads(response.content) assert data["slug"] == expected_slug assert sorted(data["tags"]) == expected_tags assert sorted(data["review_tags"]) == expected_review_tags
def test_json(doc_hierarchy, client, params_case): """Test the wiki.json endpoint.""" top_doc = doc_hierarchy.top bottom_doc = doc_hierarchy.bottom expected_tags = sorted(['foo', 'bar', 'baz']) expected_review_tags = sorted(['tech', 'editorial']) for doc in (top_doc, bottom_doc): doc.tags.set(*expected_tags) doc.current_revision.review_tags.set(*expected_review_tags) params = None expected_slug = None expected_status_code = 200 if params_case == 'nothing': expected_status_code = 400 elif params_case == 'title-only': expected_slug = top_doc.slug params = dict(title=top_doc.title) elif params_case == 'slug-only': expected_slug = bottom_doc.slug params = dict(slug=bottom_doc.slug) elif params_case == 'title-and-slug': expected_slug = top_doc.slug params = dict(title=top_doc.title, slug=bottom_doc.slug) else: # missing title expected_status_code = 404 params = dict(title='nonexistent document title') url = reverse('wiki.json') with override_switch('application_ACAO', True): response = client.get(url, params) assert response.status_code == expected_status_code if response.status_code == 404: assert_no_cache_header(response) else: assert_shared_cache_header(response) assert response['Access-Control-Allow-Origin'] == '*' if response.status_code == 200: data = json.loads(response.content) assert data['slug'] == expected_slug assert sorted(data['tags']) == expected_tags assert sorted(data['review_tags']) == expected_review_tags
def test_is_ready_for_auto_approval_addon_status(self): addon = Addon.objects.get(id=3615) addon.status = amo.STATUS_NOMINATED version = addon.current_version version.all_files = [ File(status=amo.STATUS_AWAITING_REVIEW, is_webextension=True)] assert not version.is_ready_for_auto_approval with override_switch('post-review', active=True): # When the post-review switch is active, we also accept add-ons # with NOMINATED status. assert version.is_ready_for_auto_approval addon.status = amo.STATUS_NOMINATED assert version.is_ready_for_auto_approval addon.status = amo.STATUS_DISABLED assert not version.is_ready_for_auto_approval
def test_email_with_course_comment_editing(self, is_switch_enabled): """ Verify that after editing a comment against a course emails send to multiple users. """ with override_switch(PUBLISHER_ENABLE_READ_ONLY_FIELDS, active=is_switch_enabled): comment = self.create_comment(content_object=self.course) subject = 'Comment added: {title}'.format(title=self.course.title) self.assertEqual(str(mail.outbox[0].subject), subject) self.assertIn(comment.comment, str(mail.outbox[0].body.strip())) comment.comment = 'update the comment' comment.save() subject = 'Comment updated: {title}'.format( title=self.course.title) self.assertEqual(str(mail.outbox[1].subject), subject) self.assertIn(comment.comment, str(mail.outbox[1].body.strip()), 'update the comment')
def test_has_project_and_draft_registration(self): prereg_schema = RegistrationSchema.objects.get(name='Prereg Challenge') factories.DraftRegistrationFactory(initiator=self.user, registration_schema=prereg_schema) assert_equal( landing_page(user=self.user), { 'has_projects': True, 'has_draft_registrations': True, 'campaign_long': 'Prereg Challenge', 'campaign_short': 'prereg_challenge', 'is_logged_in': True, 'sign_up_url': '{}register/?campaign=prereg&next=http%3A%2F%2Flocalhost%2F'. format(DOMAIN), }) with override_switch(name=OSF_PREREGISTRATION, active=True): prereg_schema = RegistrationSchema.objects.get( name='OSF Preregistration') factories.DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema) assert_equal( landing_page(user=self.user), { 'has_projects': True, 'has_draft_registrations': True, 'campaign_long': 'OSF Preregistration', 'campaign_short': 'prereg', 'is_logged_in': True, 'sign_up_url': '{}register/?campaign=prereg&next=http%3A%2F%2Flocalhost%2F' .format(DOMAIN), })
def test_is_ready_for_auto_approval_addon_status(self): addon = Addon.objects.get(id=3615) addon.status = amo.STATUS_NOMINATED version = addon.current_version version.all_files = [ File(status=amo.STATUS_AWAITING_REVIEW, is_webextension=True) ] assert not version.is_ready_for_auto_approval with override_switch('post-review', active=True): # When the post-review switch is active, we also accept add-ons # with NOMINATED status. assert version.is_ready_for_auto_approval addon.status = amo.STATUS_NOMINATED assert version.is_ready_for_auto_approval addon.status = amo.STATUS_DISABLED assert not version.is_ready_for_auto_approval
def test_addon_error_raises(self): responses.add(responses.POST, 'https://basket.allizom.org/amo-sync/addon/', json=True, status=403) with override_switch('basket-amo-sync', active=False): # Gotta deactivate the sync when calling addon_factory() because # the change to _current_version inside will trigger a sync. addon = addon_factory() with self.assertRaises(HTTPError): sync_object_to_basket('addon', addon.pk) assert len(responses.calls) == 1 request = responses.calls[0].request assert request.headers['x-api-key'] == '' body = request.body data = json.loads(body) expected_data = AddonBasketSyncSerializer(addon).data assert expected_data assert data == expected_data
def test_autosuggest(client, redirect_doc, doc_hierarchy, locale_case, term): params = {} expected_status_code = 200 if term: params.update(term=term) else: expected_status_code = 400 if locale_case == 'non-english-locale': params.update(locale='it') expected_titles = set(('Superiore Documento',)) elif locale_case == 'current-locale': params.update(current_locale='true') # The root document is pulled-in by the redirect_doc fixture. expected_titles = set(('Root Document', 'Top Document', 'Middle-Top Document', 'Middle-Bottom Document', 'Bottom Document')) elif locale_case == 'exclude-current-locale': params.update(exclude_current_locale='true') expected_titles = set(('Haut Document', 'Superiore Documento')) else: # All locales # The root document is pulled-in by the redirect_doc fixture. expected_titles = set(('Root Document', 'Top Document', 'Haut Document', 'Superiore Documento', 'Middle-Top Document', 'Middle-Bottom Document', 'Bottom Document')) url = reverse('wiki.autosuggest_documents') if params: url += '?{}'.format(urlencode(params)) with override_switch('application_ACAO', True): response = client.get(url) assert response.status_code == expected_status_code assert_shared_cache_header(response) assert 'Access-Control-Allow-Origin' in response assert response['Access-Control-Allow-Origin'] == '*' if expected_status_code == 200: assert response['Content-Type'] == 'application/json' data = json.loads(response.content) assert set(item['title'] for item in data) == expected_titles
def test_not_logged_in(self): assert_equal( landing_page(), { 'has_projects': False, 'has_draft_registrations': False, 'campaign_long': 'Prereg Challenge', 'campaign_short': 'prereg_challenge', 'is_logged_in': False, } ) with override_switch(name=OSF_PREREGISTRATION, active=True): assert_equal( landing_page(), { 'has_projects': False, 'has_draft_registrations': False, 'campaign_long': 'OSF Preregistration', 'campaign_short': 'prereg', 'is_logged_in': False, } )
def test_html_sidebar_enabled(self, itemfactory_display_name, itemfactory_data, waffle_switch_value): with override_switch( '{}.{}'.format( COURSE_EXPERIENCE_WAFFLE_NAMESPACE, ENABLE_COURSE_ABOUT_SIDEBAR_HTML ), active=waffle_switch_value ): if itemfactory_display_name: ItemFactory.create( category="about", parent_location=self.course.location, display_name=itemfactory_display_name, data=itemfactory_data, ) url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) if waffle_switch_value and itemfactory_display_name and itemfactory_data: self.assertIn('<section class="about-sidebar-html">', resp.content) self.assertIn(itemfactory_data, resp.content) else: self.assertNotIn('<section class="about-sidebar-html">', resp.content)
def inner(): with override_switch('foo', active=False): raise RuntimeError("Trying to break")