def test_list_tokens(self): """Test token listing.""" # create some test content content = make_content() content_2 = make_content() create_date = datetime.now() expire_date = create_date + timedelta(days=3) info_1 = ObfuscatedUrlInfo.objects.create( content=content, create_date=create_date.isoformat(), expire_date=expire_date.isoformat()) info_2 = ObfuscatedUrlInfo.objects.create( content=content, create_date=create_date.isoformat(), expire_date=expire_date.isoformat()) info_3 = ObfuscatedUrlInfo.objects.create( content=content, create_date=create_date.isoformat(), expire_date=expire_date.isoformat()) ObfuscatedUrlInfo.objects.create(content=content_2, create_date=create_date.isoformat(), expire_date=expire_date.isoformat()) # attempt to get tokens response = self.client.get( reverse("content-list-tokens", kwargs={"pk": content.id})) # check out stuff json_response = json.loads(response.content.decode("utf8")) self.assertEqual(len(json_response), 3) self.assertEqual(json_response[0]["id"], info_1.id) self.assertEqual(json_response[0]["url_uuid"], info_1.url_uuid) self.assertEqual(json_response[1]["id"], info_2.id) self.assertEqual(json_response[2]["id"], info_3.id)
def test_ordering(self): one_hour = timezone.now() + datetime.timedelta(hours=1) test_one = make_content(published=one_hour) InsertOperation.objects.create(pzone=self.pzone, when=one_hour + datetime.timedelta(hours=1), index=2, content=test_one) test_two = make_content(published=one_hour) InsertOperation.objects.create(pzone=self.pzone, when=one_hour + datetime.timedelta(hours=1), index=3, content=test_two) modified_list = PZone.objects.preview(pk=self.pzone.id, when=one_hour + datetime.timedelta(hours=3)) self.assertEqual(len(self.pzone), 10) self.assertEqual(len(modified_list), 10) self.assertEqual(len(modified_list.data), 12) self.assertEqual(modified_list[2].pk, test_one.pk) self.assertEqual(modified_list[3].pk, test_two.pk)
def test_ordering(self): one_hour = timezone.now() + datetime.timedelta(hours=1) test_one = make_content(published=one_hour) InsertOperation.objects.create( pzone=self.pzone, when=one_hour + datetime.timedelta(hours=1), index=2, content=test_one ) test_two = make_content(published=one_hour) InsertOperation.objects.create( pzone=self.pzone, when=one_hour + datetime.timedelta(hours=1), index=3, content=test_two ) modified_list = PZone.objects.preview(pk=self.pzone.id, when=one_hour + datetime.timedelta(hours=3)) self.assertEqual(len(self.pzone), 10) self.assertEqual(len(modified_list), 10) self.assertEqual(len(modified_list.data), 12) self.assertEqual(modified_list[2].pk, test_one.pk) self.assertEqual(modified_list[3].pk, test_two.pk)
def test_list_tokens(self): """Test token listing.""" # create some test content content = make_content() content_2 = make_content() create_date = datetime.now() expire_date = create_date + timedelta(days=3) info_1 = ObfuscatedUrlInfo.objects.create( content=content, create_date=create_date.isoformat(), expire_date=expire_date.isoformat()) info_2 = ObfuscatedUrlInfo.objects.create( content=content, create_date=create_date.isoformat(), expire_date=expire_date.isoformat()) info_3 = ObfuscatedUrlInfo.objects.create( content=content, create_date=create_date.isoformat(), expire_date=expire_date.isoformat()) ObfuscatedUrlInfo.objects.create( content=content_2, create_date=create_date.isoformat(), expire_date=expire_date.isoformat()) # attempt to get tokens response = self.client.get(reverse("content-list-tokens", kwargs={"pk": content.id})) # check out stuff json_response = json.loads(response.content.decode("utf8")) self.assertEqual(len(json_response), 3) self.assertEqual(json_response[0]["id"], info_1.id) self.assertEqual(json_response[0]["url_uuid"], info_1.url_uuid) self.assertEqual(json_response[1]["id"], info_2.id) self.assertEqual(json_response[2]["id"], info_3.id)
def test_post_operations(self): """Test that a new operation can be added to a pzone operations.""" # test objects test_time = (timezone.now() + datetime.timedelta(hours=1)).replace(microsecond=0) test_content_1 = make_content(published=timezone.now()) test_content_2 = make_content(published=timezone.now()) # setup and query endpoint endpoint = reverse("pzone_operations", kwargs={"pzone_pk": self.pzone.pk}) response = self.client.post(endpoint, json.dumps([ { "type_name": "promotion_replaceoperation", "pzone": self.pzone.pk, "when": test_time.isoformat(), "index": 1, "content": test_content_1.id }, { "type_name": "promotion_replaceoperation", "pzone": self.pzone.pk, "when": test_time.isoformat(), "index": 2, "content": test_content_2.id }, ]), content_type="application/json") # check that we got an OK response self.assertEqual(response.status_code, 200, msg=response.data) # check that operations made it into the db self.assertEqual(PZoneOperation.objects.count(), 2) # check response data data operations = response.data self.assertNotEqual(operations[0]["id"], None) self.assertEqual(operations[0]["type_name"], "promotion_replaceoperation") self.assertEqual(operations[0]["pzone"], self.pzone.pk) self.assertEqual(operations[0]["when"], test_time.isoformat().replace("+00:00", "Z")) self.assertEqual(operations[0]["index"], 1) self.assertEqual(operations[0]["content"], test_content_1.id) assert operations[1]["id"] > operations[0]["id"] self.assertEqual(operations[1]["type_name"], "promotion_replaceoperation") self.assertEqual(operations[1]["pzone"], self.pzone.pk) self.assertEqual(operations[1]["when"], test_time.isoformat().replace("+00:00", "Z")) self.assertEqual(operations[1]["index"], 2) self.assertEqual(operations[1]["content"], test_content_2.id)
def test_setitem(self): new_content = make_content(TestContentObj) self.pzone[0] = new_content self.assertEqual(self.pzone[0].pk, new_content.pk) newer_content = make_content(TestContentObj) self.pzone[1] = newer_content.id self.assertEqual(self.pzone[1].pk, newer_content.pk)
def setUp(self): super(MigrateIAFeatureTypeTestCase, self).setUp() self.featuretype = FeatureType.objects.create(name="News in Brief") self.non_ia_featuretype = FeatureType.objects.create(name="Blah Blah") make_content(TestContentObj, published=self.now, feature_type=self.featuretype, _quantity=50)
def test_excluded_doc_types_configured(self): make_content(AnotherTestReadingListObj, published=self.now, _quantity=50) Content.search_objects.refresh() self.assertEqual(Content.search_objects.count(), 55) reading_list = self.query_content[0].get_reading_list_context( )["content"] self.assertEqual(reading_list.default_queryset.count(), 4)
def test_resolve_redirect_url(self): make_content(id=123) for test_url in ('http://test.local/r/123', '/r/123tsd', '/r/123?one=two&three=four', 'http://test.local/r/123', 'http://test.local/r/123?one=two'): r = self.resolve(url=test_url) self.assertEqual(r.status_code, 200) self.assertEqual(123, r.data['id'])
def setUp(self): super(PopularContentTestCase, self).setUp() self.popular_content = make_content( published=self.now - timezone.timedelta(days=10), _quantity=10 ) self.recent_content = make_content(published=self.now, _quantity=10) self.expected_ingest_response = [obj.id for obj in self.popular_content] self.malformed_ingest_response = {obj.title: obj.id for obj in self.popular_content} Content.search_objects.refresh()
def test_resolve_custom_content_url(self): # Simulate app-specific content URL class ContentUrls(object): urlpatterns = (bulbs.api.urls.urlpatterns + (url(r"^article/(?P<slug>[\w-]*)-(?P<pk>\d+)$", mock.Mock()),)) make_content(id=123) with override_settings(ROOT_URLCONF=ContentUrls): r = self.resolve(url="/article/some-slug-123?one=two") self.assertEqual(r.status_code, 200) self.assertEqual(123, r.data['id'])
def test_contains(self): newer_content = make_content(TestContentObj) self.pzone[1] = newer_content.id self.assertTrue(newer_content.pk in self.pzone) self.assertTrue(newer_content in self.pzone) invisible_content = make_content(TestContentObj) self.assertFalse(invisible_content.pk in self.pzone) self.assertFalse(invisible_content in self.pzone)
def setUp(self): super(MigrateIAFeatureTypeTestCase, self).setUp() self.featuretype = FeatureType.objects.create(name="News in Brief") self.non_ia_featuretype = FeatureType.objects.create(name="Blah Blah") make_content( TestContentObj, published=self.now, feature_type=self.featuretype, _quantity=50 )
def setUp(self): super(AugmentedReadingListTestCase, self).setUp() # Fill up recent with more content make_content(TestReadingListObj, published=self.now, _quantity=50) self.sponsored_content = make_content(TestReadingListObj, published=self.now - timezone.timedelta(hours=9), tunic_campaign_id=1, _quantity=20) Content.search_objects.refresh()
def setUp(self): super(VideoRedirectViewTestCase, self).setUp() self.view = VideoRedirectView() self.videohub_video = VideohubVideo.objects.create(id=4382) self.older_video = make_content( TestVideoContentObj, videohub_ref=self.videohub_video, published=timezone.now() ) self.newer_video = make_content( TestVideoContentObj, videohub_ref=self.videohub_video, published=timezone.now() )
def setUp(self): super(VideoRedirectViewTestCase, self).setUp() self.view = VideoRedirectView() self.videohub_video = VideohubVideo.objects.create(id=4382) self.older_video = make_content(TestVideoContentObj, videohub_ref=self.videohub_video, published=timezone.now()) self.newer_video = make_content(TestVideoContentObj, videohub_ref=self.videohub_video, published=timezone.now())
def test_post_operations(self): """Test that a new operation can be added to a pzone operations.""" # test objects test_time = (timezone.now() + datetime.timedelta(hours=1)).replace(microsecond=0) test_content_1 = make_content(published=timezone.now()) test_content_2 = make_content(published=timezone.now()) # setup and query endpoint endpoint = reverse("pzone_operations", kwargs={ "pzone_pk": self.pzone.pk }) response = self.client.post( endpoint, json.dumps([ { "type_name": "promotion_replaceoperation", "pzone": self.pzone.pk, "when": test_time.isoformat(), "index": 1, "content": test_content_1.id }, { "type_name": "promotion_replaceoperation", "pzone": self.pzone.pk, "when": test_time.isoformat(), "index": 2, "content": test_content_2.id }, ]), content_type="application/json" ) # check that we got an OK response self.assertEqual(response.status_code, 200, msg=response.data) # check that operations made it into the db self.assertEqual(PZoneOperation.objects.count(), 2) # check response data data operations = response.data self.assertNotEqual(operations[0]["id"], None) self.assertEqual(operations[0]["type_name"], "promotion_replaceoperation") self.assertEqual(operations[0]["pzone"], self.pzone.pk) self.assertEqual(operations[0]["when"], test_time.isoformat().replace("+00:00", "Z")) self.assertEqual(operations[0]["index"], 1) self.assertEqual(operations[0]["content"], test_content_1.id) assert operations[1]["id"] > operations[0]["id"] self.assertEqual(operations[1]["type_name"], "promotion_replaceoperation") self.assertEqual(operations[1]["pzone"], self.pzone.pk) self.assertEqual(operations[1]["when"], test_time.isoformat().replace("+00:00", "Z")) self.assertEqual(operations[1]["index"], 2) self.assertEqual(operations[1]["content"], test_content_2.id)
def test_resolve_custom_content_url(self): # Simulate app-specific content URL class ContentUrls(object): urlpatterns = (bulbs.api.urls.urlpatterns + (url( r"^article/(?P<slug>[\w-]*)-(?P<pk>\d+)$", mock.Mock()), )) make_content(id=123) with override_settings(ROOT_URLCONF=ContentUrls): r = self.resolve(url="/article/some-slug-123?one=two") self.assertEqual(r.status_code, 200) self.assertEqual(123, r.data['id'])
def setUp(self): super(AugmentedReadingListTestCase, self).setUp() # Fill up recent with more content make_content(TestReadingListObj, published=self.now, _quantity=50) self.sponsored_content = make_content( TestReadingListObj, published=self.now - timezone.timedelta(hours=9), tunic_campaign_id=1, _quantity=20 ) Content.search_objects.refresh()
def test_pagination_bounds_404(self): # One page past last should trigger 404 make_content(TestContentObj, published=datetime(2016, 5, 2, 14, 43, 0, tzinfo=timezone.utc)) self.get_feed(page=2, page_size=1, status_code=404)
def setUp(self): super(BaseIndexableFeatureTypeTestCase, self).setUp() self.featuretype = FeatureType.objects.create(name="News in Brief") # Published Instant Articles make_content(TestContentObj, published=self.now, feature_type=self.featuretype, _quantity=50) # Unpublished Instant Articles make_content(TestContentObj, feature_type=self.featuretype, _quantity=50)
def test_rss_feed(self): # Let's bust out some content make_content(TestContentObj, published=timezone.now() - timedelta(hours=2), _quantity=35) TestContentObj.search_objects.refresh() rss_endpoint = reverse("rss-feed") client = Client() response = client.get(rss_endpoint) self.assertEqual(response.status_code, 200) first_item = response.context["page_obj"].object_list[0] self.assertTrue(hasattr(first_item, "feed_url"))
def test_get_operations(self): """Test that we can get a pzone's operations.""" # set up some test operations test_time = (timezone.now() + datetime.timedelta(hours=-1)).replace(microsecond=0) new_content_1 = make_content() op_1 = InsertOperation.objects.create(pzone=self.pzone, when=test_time, index=0, content=new_content_1) op_1_type = "{}_{}".format(op_1.polymorphic_ctype.app_label, op_1.polymorphic_ctype.model) # this one should end up above the first one new_content_2 = make_content() op_2 = InsertOperation.objects.create(pzone=self.pzone, when=test_time, index=0, content=new_content_2) op_2_type = "{}_{}".format(op_2.polymorphic_ctype.app_label, op_2.polymorphic_ctype.model) # query the endpoint endpoint = reverse("pzone_operations", kwargs={"pzone_pk": self.pzone.pk}) response = self.client.get(endpoint) # check that we got an OK response self.assertEqual(response.status_code, 200, msg=response.data) # start checking data operations = response.data self.assertEqual(len(operations), 2) # check first operation made it in self.assertEqual(operations[0]["type_name"], op_1_type) self.assertEqual(operations[0]["content"], new_content_1.pk) self.assertEqual(operations[0]["pzone"], self.pzone.pk) self.assertEqual(operations[0]["index"], 0) self.assertEqual(operations[0]["content_title"], new_content_1.title) self.assertEqual(operations[0]["when"], test_time.isoformat().replace("+00:00", "Z")) # check second operation made it in self.assertEqual(operations[1]["type_name"], op_2_type) self.assertEqual(operations[1]["content"], new_content_2.pk) self.assertEqual(operations[1]["pzone"], self.pzone.pk) self.assertEqual(operations[1]["index"], 0) self.assertEqual(operations[1]["content_title"], new_content_2.title) self.assertEqual(operations[1]["when"], test_time.isoformat().replace("+00:00", "Z"))
def test_get_operations(self): """Test that we can get a pzone's operations.""" # set up some test operations test_time = (timezone.now() + datetime.timedelta(hours=-1)).replace(microsecond=0) new_content_1 = make_content() op_1 = InsertOperation.objects.create( pzone=self.pzone, when=test_time, index=0, content=new_content_1 ) op_1_type = "{}_{}".format(op_1.polymorphic_ctype.app_label, op_1.polymorphic_ctype.model) # this one should end up above the first one new_content_2 = make_content() op_2 = InsertOperation.objects.create( pzone=self.pzone, when=test_time, index=0, content=new_content_2 ) op_2_type = "{}_{}".format(op_2.polymorphic_ctype.app_label, op_2.polymorphic_ctype.model) # query the endpoint endpoint = reverse("pzone_operations", kwargs={ "pzone_pk": self.pzone.pk }) response = self.client.get(endpoint) # check that we got an OK response self.assertEqual(response.status_code, 200, msg=response.data) # start checking data operations = response.data self.assertEqual(len(operations), 2) # check first operation made it in self.assertEqual(operations[0]["type_name"], op_1_type) self.assertEqual(operations[0]["content"], new_content_1.pk) self.assertEqual(operations[0]["pzone"], self.pzone.pk) self.assertEqual(operations[0]["index"], 0) self.assertEqual(operations[0]["content_title"], new_content_1.title) self.assertEqual(operations[0]["when"], test_time.isoformat().replace("+00:00", "Z")) # check second operation made it in self.assertEqual(operations[1]["type_name"], op_2_type) self.assertEqual(operations[1]["content"], new_content_2.pk) self.assertEqual(operations[1]["pzone"], self.pzone.pk) self.assertEqual(operations[1]["index"], 0) self.assertEqual(operations[1]["content_title"], new_content_2.title) self.assertEqual(operations[1]["when"], test_time.isoformat().replace("+00:00", "Z"))
def setUp(self): super(PopularContentTestCase, self).setUp() self.popular_content = make_content(published=self.now - timezone.timedelta(days=10), _quantity=10) self.recent_content = make_content(published=self.now, _quantity=10) self.expected_ingest_response = [ obj.id for obj in self.popular_content ] self.malformed_ingest_response = { obj.title: obj.id for obj in self.popular_content } Content.search_objects.refresh()
def test_reporting_api(self): content_one = make_content(published=timezone.now() - datetime.timedelta(days=1)) content_two = make_content(published=timezone.now() - datetime.timedelta(days=3)) for content in content_one, content_two: Contribution.objects.create( content=content, contributor=self.chris, role=self.roles["editor"] ) Contribution.objects.create( content=content, contributor=self.mike, role=self.roles["writer"] ) client = Client() client.login(username="******", password="******") # Let's look at all the items endpoint = reverse("contributionreporting-list") start_date = timezone.now() - datetime.timedelta(days=4) response = client.get(endpoint, data={"start": start_date.strftime("%Y-%m-%d")}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 4) # Now lets order by something else response = client.get(endpoint, data={"start": start_date.strftime("%Y-%m-%d"), "ordering": "user"}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 4) # Now let's filter by date start_date = timezone.now() - datetime.timedelta(days=2) response = client.get(endpoint, data={"start": start_date.strftime("%Y-%m-%d")}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 2) # Now let's check the CSV output start_date = timezone.now() - datetime.timedelta(days=4) response = client.get(endpoint, data={"start": start_date.strftime("%Y-%m-%d"), "format": "csv"}) self.assertEqual(response.status_code, 200) csvreader = csv.DictReader(StringIO.StringIO(response.content.decode("utf8"))) self.assertEqual(len(csvreader.fieldnames), 12) for line in csvreader: pass self.assertEqual(csvreader.line_num, 5) # Header + 4 items
def test_freelance_reporting(self): client = Client() client.login(username="******", password="******") endpoint = reverse("freelancereporting-list") start_date = timezone.now() - datetime.timedelta(days=4) topdog = User.objects.create(username="******", first_name="Top", last_name="Dog", is_staff=True) FreelanceProfile.objects.create(contributor=topdog) otherdog = User.objects.create(username="******", first_name="Other", last_name="Dog", is_staff=True) FreelanceProfile.objects.create(contributor=otherdog) content_one = make_content(published=timezone.now() - datetime.timedelta(days=1)) Contribution.objects.create(content=content_one, contributor=topdog, role=self.roles["editor"]) Contribution.objects.create(content=content_one, contributor=otherdog, role=self.roles["editor"]) Contribution.objects.create(content=content_one, contributor=topdog, role=self.roles["writer"]) response = client.get(endpoint, data={"start": start_date.strftime("%Y-%m-%d")}) self.assertEqual(response.status_code, 200)
def test_content_list_views(self): ft = FeatureType.objects.create(name="Feature", slug="feature") content = make_content(TestContentObj, feature_type=ft, published=timezone.now() - timedelta(hours=2)) content_two = make_content(TestContentObjTwo, feature_type=ft, published=timezone.now() - timedelta(hours=2)) Content.search_objects.refresh() # make sure we get all content with this list r = self.client.get(reverse("example.testcontent.views.test_all_content_list")) self.assertEqual(r.status_code, 200) self.assertEqual(2, len(r.context_data["content_list"])) # make sure we only get TestContentTwoObjs from this other list r = self.client.get(reverse("example.testcontent.views.test_content_two_list")) self.assertEqual(r.status_code, 200) self.assertEqual(1, len(r.context_data["content_list"])) item = r.context_data["content_list"][0] ctype = ContentType.objects.get_for_id(item.polymorphic_ctype_id) self.assertIs(ctype.model_class(), TestContentObjTwo)
def test_inactive_special_coverage_view(self): content = make_content(published=timezone.now()) content.__class__.search_objects.refresh() # create old special coverage sc = SpecialCoverage.objects.create( name="Test Coverage", slug="test-coverage", description="Testing special coverage", query={ "included_ids": [content.id] }, videos=[], start_date=timezone.now() - timezone.timedelta(days=20), end_date=timezone.now() - timezone.timedelta(days=10) ) special_url = reverse("special", kwargs={"slug": sc.slug}) # Default - 404 response = self.client.get(special_url) self.assertEqual(response.status_code, 404) # Full preview mode - non-Staff redirect response = self.client.get(special_url + '?full_preview=true') self.assertEqual(response.status_code, 302) self.assertEqual( response['Location'], 'http://testserver/accounts/login/?next=%2Fspecial%2Ftest-coverage%3Ffull_preview%3Dtrue') # Full preview mode - Staff OK self.client.login(username='******', password='******') response = self.client.get(special_url + '?full_preview=true') self.assertEqual(response.status_code, 200)
def test_add_remove_tags(self): content = make_content() original_tag_count = len(content.tags.all()) new_tag = Tag.objects.create(name='crankdat') content.tags.add(new_tag) self.assertEqual(len(content.tags.all()), original_tag_count + 1) self.assertEqual(len(content.tags.all()), len(content.to_dict()["tags"]))
def test_publish_now(self): content = make_content( TestContentObj, title="Django Unchained: How a framework tried to run using async IO", description="Spoiler alert: it didn't go great, unless you measure by # of HN articles", foo="SUCK IT, NERDS.", published=None ) client = Client() client.login(username="******", password="******") # ensure permission to publish content_rest_url = reverse("content-publish", kwargs={"pk": content.id}) response = client.post(content_rest_url, content_type="application/json") self.assertEqual(response.status_code, 403) self.give_permissions() # ok now it should work response = client.post(content_rest_url, content_type="application/json") self.assertEqual(response.status_code, 200) response_data = response.data self.assertEqual(response_data["status"], "final") # assert that we can load it up article = Content.objects.get(id=content.id) self.assertIsNotNone(article.published) # check for a log LogEntry.objects.filter(object_id=article.pk).get(change_message="final")
def test_special_coverage_view(self): content = make_content(published=timezone.now()) content.__class__.search_objects.refresh() sc = SpecialCoverage.objects.create( name="Test Coverage", slug="test-coverage", description="Testing special coverage", query={ "included_ids": [content.id] }, videos=[], start_date=timezone.now() - timezone.timedelta(days=10), end_date=timezone.now() + timezone.timedelta(days=10) ) response = self.client.get(reverse("special", kwargs={"slug": sc.slug})) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['special_coverage'], sc) self.assertEqual(response.context['content_list'].count(), sc.get_content().count()) self.assertEqual(response.context['content_list'][0].id, content.id) self.assertEqual(response.context['current_video'], None) self.assertEqual(response.context['targeting'], { 'dfp_specialcoverage': 'test-coverage', }) self.assertEqual( response.template_name[0], 'special_coverage/custom/test_coverage_custom.html' ) self.assertEqual(response.template_name[1], 'special_coverage/landing.html')
def test_delete_operation(self): """Test that we can remove an operation from a pzone.""" # add an operation to the db test_time = timezone.now() + datetime.timedelta(hours=1) new_content = make_content() new_operation = InsertOperation.objects.create( pzone=self.pzone, when=test_time, index=0, content=new_content ) # setup and query endpoint endpoint = reverse("pzone_operations_delete", kwargs={ "pzone_pk": self.pzone.pk, "operation_pk": new_operation.pk }) response = self.client.delete(endpoint) # check that we got an No Content (204) response self.assertEqual(response.status_code, 204, msg=response.data) # start checking data self.assertEqual(InsertOperation.objects.count(), 0)
def create_content(self): self.author = User.objects.create( username="******", first_name="Chris", last_name="Sinchok" ) self.content = make_content(TestContentObj, foo="booyah")
def test_publish_specific(self): content = make_content(published=None) client = Client() client.login(username="******", password="******") content_rest_url = reverse("content-publish", kwargs={"pk": content.id}) response = client.post(content_rest_url, data=json.dumps( {"published": "2013-06-09T00:00:00-06:00"}), content_type="application/json") # no permissions, no publish self.assertEqual(response.status_code, 403) self.give_permissions() # now it should work response = client.post(content_rest_url, data=json.dumps( {"published": "2013-06-09T00:00:00-06:00"}), content_type="application/json") self.assertEqual(response.status_code, 200) response_data = response.data self.assertEqual(response_data["status"], "final") # assert that we can load it up article = Content.objects.get(id=content.id) self.assertEqual(article.published.year, 2013) self.assertEqual(article.published.month, 6) self.assertEqual(article.published.day, 9) # check for a log LogEntry.objects.filter(object_id=article.pk).get( change_message="final")
def test_evergreen_video(self): videohub_ref = VideohubVideo.objects.create(id=1) expected = make_content(TestVideoContentObj, videohub_ref=videohub_ref, evergreen=True, published=self.now, _quantity=12) # Ignored content make_content(TestVideoContentObj, videohub_ref=videohub_ref, published=self.now, _quantity=12) # Not evergreen make_content(TestVideoContentObj, evergreen=True, published=self.now) # No video ref Content.search_objects.refresh() evergreen = Content.search_objects.evergreen_video()[:50] self.assertEqual(12, evergreen.count()) self.assertEqual( sorted([o.id for o in expected]), sorted([o.id for o in evergreen]) )
def test_prevent_replace_of_article_with_future_publish_date(self): """Insert operations should not complete on articles with a publish date in the future.""" new_content = make_content() # article has a future published date new_content.published = timezone.now() + datetime.timedelta(hours=2) # check old value at index where we're inserting index = 0 old_id = self.pzone[index].id # attempt to insert ReplaceOperation.objects.create( pzone=self.pzone, when=timezone.now() + datetime.timedelta(hours=-1), index=index, content=new_content ) PZone.objects.operate_on(pk=self.pzone.id, apply=True) # get pzone again self.pzone = PZone.objects.get(id=self.pzone.id) # make sure the pzone has not been modified self.assertEqual(old_id, self.pzone[index].id)
def test_unpublish(self): content = make_content(published=timezone.now()) client = Client() client.login(username="******", password="******") content_rest_url = reverse("content-publish", kwargs={"pk": content.id}) response = client.post(content_rest_url, data=json.dumps({"published": False}), content_type="application/json") # no permissions, no unpublish self.assertEqual(response.status_code, 403) self.give_permissions() # now it should work response = client.post(content_rest_url, data=json.dumps({"published": False}), content_type="application/json") # ensure it was created and got an id self.assertEqual(response.status_code, 200) response_data = response.data self.assertEqual(response_data["status"], "draft") # assert that we can load it up article = Content.objects.get(id=content.id) self.assertEqual(article.published, None) # check for a log LogEntry.objects.filter(object_id=article.pk).get( change_message="draft")
def test_author_publish_permissions(self): content = make_content(published=None) content.authors.add(self.admin) client = Client() client.login(username="******", password="******") # ensure permission to publish content_rest_url = reverse("content-publish", kwargs={"pk": content.id}) response = client.post(content_rest_url, content_type="application/json") print(response.content) self.assertEqual(response.status_code, 403) self.give_author_permissions() # ok now it should work response = client.post(content_rest_url, content_type="application/json") self.assertEqual(response.status_code, 200) response_data = response.data self.assertEqual(response_data["status"], "final") # assert that we can load it up article = Content.objects.get(id=content.id) self.assertIsNotNone(article.published) # check for a log LogEntry.objects.filter(object_id=article.pk).get( change_message="final")
def test_prevent_replace_of_article_with_future_publish_date(self): """Insert operations should not complete on articles with a publish date in the future.""" new_content = make_content() # article has a future published date new_content.published = timezone.now() + datetime.timedelta(hours=2) # check old value at index where we're inserting index = 0 old_id = self.pzone[index].id # attempt to insert ReplaceOperation.objects.create(pzone=self.pzone, when=timezone.now() + datetime.timedelta(hours=-1), index=index, content=new_content) PZone.objects.operate_on(pk=self.pzone.id, apply=True) # get pzone again self.pzone = PZone.objects.get(id=self.pzone.id) # make sure the pzone has not been modified self.assertEqual(old_id, self.pzone[index].id)
def test_publish_specific(self): content = make_content(published=None) client = Client() client.login(username="******", password="******") content_rest_url = reverse("content-publish", kwargs={"pk": content.id}) response = client.post( content_rest_url, data=json.dumps({"published": "2013-06-09T00:00:00-06:00"}), content_type="application/json") # no permissions, no publish self.assertEqual(response.status_code, 403) self.give_permissions() # now it should work response = client.post( content_rest_url, data=json.dumps({"published": "2013-06-09T00:00:00-06:00"}), content_type="application/json") self.assertEqual(response.status_code, 200) response_data = response.data self.assertEqual(response_data["status"], "final") # assert that we can load it up article = Content.objects.get(id=content.id) self.assertEqual(article.published.year, 2013) self.assertEqual(article.published.month, 6) self.assertEqual(article.published.day, 9) # check for a log LogEntry.objects.filter(object_id=article.pk).get(change_message="final")
def test_unpublish(self): content = make_content(published=timezone.now()) client = Client() client.login(username="******", password="******") content_rest_url = reverse("content-publish", kwargs={"pk": content.id}) response = client.post( content_rest_url, data=json.dumps({"published": False}), content_type="application/json") # no permissions, no unpublish self.assertEqual(response.status_code, 403) self.give_permissions() # now it should work response = client.post( content_rest_url, data=json.dumps({"published": False}), content_type="application/json") # ensure it was created and got an id self.assertEqual(response.status_code, 200) response_data = response.data self.assertEqual(response_data["status"], "draft") # assert that we can load it up article = Content.objects.get(id=content.id) self.assertEqual(article.published, None) # check for a log LogEntry.objects.filter(object_id=article.pk).get(change_message="draft")
def test_contributions_create_api(self): client = Client() client.login(username="******", password="******") content = make_content() Content.search_objects.refresh() self.assertEqual(Contribution.objects.filter(content=content).count(), 0) endpoint = reverse("content-contributions", kwargs={"pk": content.pk}) data = [{ "contributor": { "username": self.admin.username, "id": self.admin.id }, "content": content.id }] response = client.post(endpoint, json.dumps(data), content_type="application/json") self.assertEqual(response.status_code, 400) self.assertEqual(Contribution.objects.filter(content=content).count(), 0) data = [{ "contributor": { "username": self.admin.username, "id": self.admin.id }, "role": self.roles["writer"].id, "content": content.id }] response = client.post(endpoint, json.dumps(data), content_type="application/json") print(response.content) self.assertEqual(response.status_code, 200) self.assertEqual(Contribution.objects.filter(content=content).count(), 1)
def test_contribution_post_rate(self): client = Client() client.login(username="******", password="******") content = make_content() Content.objects.get(id=content.id) endpoint = reverse("content-contributions", kwargs={"pk": content.pk}) rate_data = "667" contributor_data = { "username": self.admin.username, "id": self.admin.id } contribution_data = [{ "rate": rate_data, "contributor": contributor_data, "content": content.id, "force_payment": True, "role": self.roles["editor"].id }] response = client.post( endpoint, json.dumps(contribution_data), content_type="application/json") contribution = response.data[0] contributor = contribution.get('contributor') rate = contribution.get('rate') self.assertEqual(response.status_code, 200) self.assertEqual(contributor['username'], 'admin') self.assertEqual(contributor['id'], self.admin.id) self.assertEqual(rate['rate'], 667) self.assertEqual(rate['name'], 'Manual') self.assertEqual(contribution['content'], content.id), self.assertEqual(contribution["force_payment"], True) self.assertEqual(contribution['role']['id'], 1)
def test_prevent_replace_of_article_already_in_pzone(self): """Replace operations should not allow an article to be inserted that already exists in the pzone.""" new_content = make_content(published=timezone.now() - datetime.timedelta(hours=2)) # do first operation InsertOperation.objects.create(pzone=self.pzone, when=timezone.now() - datetime.timedelta(hours=1), index=0, content=new_content) # do another insert operation ReplaceOperation.objects.create(pzone=self.pzone, when=timezone.now() - datetime.timedelta(hours=1), index=1, content=new_content) # get pzone again self.pzone = PZone.objects.applied(id=self.pzone.id) # check that state is correct self.assertEqual(self.pzone[0].pk, new_content.pk) self.assertNotEqual(self.pzone[1].pk, new_content.pk)
def test_prevent_replace_of_article_already_in_pzone(self): """Replace operations should not allow an article to be inserted that already exists in the pzone.""" new_content = make_content( published=timezone.now() - datetime.timedelta(hours=2) ) # do first operation InsertOperation.objects.create( pzone=self.pzone, when=timezone.now() - datetime.timedelta(hours=1), index=0, content=new_content ) # do another insert operation ReplaceOperation.objects.create( pzone=self.pzone, when=timezone.now() - datetime.timedelta(hours=1), index=1, content=new_content ) # get pzone again self.pzone = PZone.objects.applied(id=self.pzone.id) # check that state is correct self.assertEqual(self.pzone[0].pk, new_content.pk) self.assertNotEqual(self.pzone[1].pk, new_content.pk)
def test_publish_now(self): content = make_content( TestContentObj, title= "Django Unchained: How a framework tried to run using async IO", description= "Spoiler alert: it didn't go great, unless you measure by # of HN articles", foo="SUCK IT, NERDS.", published=None) client = Client() client.login(username="******", password="******") # ensure permission to publish content_rest_url = reverse("content-publish", kwargs={"pk": content.id}) response = client.post(content_rest_url, content_type="application/json") self.assertEqual(response.status_code, 403) self.give_permissions() # ok now it should work response = client.post(content_rest_url, content_type="application/json") self.assertEqual(response.status_code, 200) response_data = response.data self.assertEqual(response_data["status"], "final") # assert that we can load it up article = Content.objects.get(id=content.id) self.assertIsNotNone(article.published) # check for a log LogEntry.objects.filter(object_id=article.pk).get( change_message="final")
def setUp(self): super(ContentManagerTestCase, self).setUp() self.instant_feature_type = FeatureType.objects.create( name="Da Gahbage", instant_article=True) self.feature_type = FeatureType.objects.create(name="Insult corner", instant_article=False) make_content(TestReadingListObj, feature_type=self.instant_feature_type, evergreen=True, published=timezone.now(), _quantity=50) make_content(TestContentObj, feature_type=self.feature_type, published=timezone.now(), _quantity=50) Content.search_objects.refresh()
def test_is_published(self): content = make_content(published=None) self.assertFalse(content.is_published) content.published = timezone.now() - datetime.timedelta(hours=1) self.assertTrue(content.is_published) content.published = timezone.now() + datetime.timedelta(hours=1) self.assertFalse(content.is_published)
def setUp(self): super(PZoneOperationsTestCase, self).setUp() self.pzone = PZone.objects.create(name="homepage", zone_length=10) data = [] for i in range(10): data.append({"id": make_content().pk}) self.pzone.data = data self.pzone.save()
def test_recirc_content(self): content = make_content(_quantity=3) liveblog = TestLiveBlog.objects.create() liveblog.recirc_content.add(*content) liveblog.save() six.assertCountEqual(self, liveblog.recirc_content.all(), content) self.assertEqual(liveblog, content[0].liveblog_recirc.first())
def setUp(self): super(PolyContentTestCase, self).setUp() """ Normally, the "Content" class picks up available doctypes from installed apps, but in this case, our test models don't exist in a real app, so we'll hack them on. """ # generate some data one_hour_ago = timezone.now() - datetime.timedelta(hours=1) two_days_ago = timezone.now() - datetime.timedelta(days=2) words = ['spam', 'driver', 'dump truck', 'restaurant'] self.num_subclasses = 2 self.combos = list(itertools.combinations(words, 2)) self.all_tags = [] ft_one = FeatureType.objects.create(name="Obj one", slug="obj-one") ft_two = FeatureType.objects.create(name="Obj two", slug="obj-two") for i, combo in enumerate(self.combos): tags = [] for atom in combo: tag, created = Tag.objects.get_or_create(name=atom, slug=slugify(atom)) tags.append(tag) self.all_tags.append(tag) obj = make_content( TestContentObj, published=one_hour_ago, feature_type=ft_one, tunic_campaign_id=1 ) obj.tags.add(*tags) obj.index() obj2 = make_content(TestContentObjTwo, published=two_days_ago, feature_type=ft_two) obj2.tags.add(*tags) obj2.index() obj = TestContentObj.objects.create( title="Unpublished draft", description="Just to throw a wrench", foo="bar", feature_type=ft_one ) Content.search_objects.refresh()