How to use article method in storybook-root

Best JavaScript code snippet using storybook-root

article.js

Source:article.js Github

copy

Full Screen

1/*2 * Copyright (c) 2010-2018, b3log.org & hacpai.com3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16/**17 * @fileoverview article for admin18 *19 * @author <a href="http://vanessa.b3log.org">Liyuan Li</a>20 * @author <a href="http://88250.b3log.org">Liang Ding</a>21 * @version 1.5.0.0, Feb 25, 201822 */23admin.article = {24 currentEditorType: '',25 // 当发文章,取消发布,更新文章时设置为 false。不需在离开编辑器时进行提示。26 isConfirm: true,27 status: {28 id: undefined,29 isArticle: undefined,30 articleHadBeenPublished: undefined31 },32 content: "",33 // 自动保存草稿定时器34 autoSaveDraftTimer: "",35 // 自动保存间隔36 AUTOSAVETIME: 1000 * 60,37 /**38 * 初始化上传组建39 */40 initUploadFile: function (id) {41 var filename = "";42 $('#' + id).fileupload({43 multipart: true,44 url: "https://up.qbox.me",45 add: function (e, data) {46 filename = data.files[0].name;47 data.submit();48 $('#' + id + ' span').text('uploading...');49 },50 formData: function (form) {51 var data = form.serializeArray();52 var ext = filename.substring(filename.lastIndexOf(".") + 1);53 data.push({name: 'key', value: getUUID() + "." + ext});54 data.push({name: 'token', value: qiniu.qiniuUploadToken});55 return data;56 },57 done: function (e, data) {58 $('#' + id + ' span').text('');59 var qiniuKey = data.result.key;60 if (!qiniuKey) {61 alert("Upload error, please check Qiniu configurations");62 return;63 }64 $('#' + id).after('<div>![' + data.files[0].name + '](http://'65 + qiniu.qiniuDomain + qiniuKey + ')</div>');66 },67 fail: function (e, data) {68 $('#' + id + ' span').text("Upload error, please check Qiniu configurations [" + data.errorThrown + "]");69 }70 }).on('fileuploadprocessalways', function (e, data) {71 var currentFile = data.files[data.index];72 if (data.files.error && currentFile.error) {73 alert(currentFile.error);74 }75 });76 },77 /**78 * @description 获取文章并把值塞入发布文章页面 79 * @param {String} id 文章 id80 * @param {Boolean} isArticle 文章或者草稿81 */82 get: function (id, isArticle) {83 this.status.id = id;84 this.status.isArticle = isArticle;85 admin.selectTab("article/article");86 },87 /**88 * @description 获取文章内容89 */90 getAndSet: function () {91 $("#loadMsg").text(Label.loadingLabel);92 $("#tipMsg").text("");93 $.ajax({94 url: latkeConfig.servePath + "/console/article/" + admin.article.status.id,95 type: "GET",96 cache: false,97 success: function (result, textStatus) {98 $("#tipMsg").text(result.msg);99 if (!result.sc) {100 $("#loadMsg").text("");101 return;102 }103 // set default value for article.104 $("#title").val(result.article.articleTitle);105 admin.article.status.articleHadBeenPublished = result.article.articleHadBeenPublished;106 if (admin.article.currentEditorType !== result.article.articleEditorType) {107 admin.editors.articleEditor.remove();108 admin.editors.abstractEditor.remove();109 admin.article.currentEditorType = result.article.articleEditorType;110 admin.editors.articleEditor.init(result.article.articleEditorType);111 admin.editors.abstractEditor.init(result.article.articleEditorType);112 }113 admin.editors.articleEditor.setContent(result.article.articleContent);114 admin.editors.abstractEditor.setContent(result.article.articleAbstract);115 admin.article.content = admin.editors.articleEditor.getContent();116 var tags = result.article.articleTags,117 tagsString = '';118 for (var i = 0; i < tags.length; i++) {119 if (0 === i) {120 tagsString = tags[i].tagTitle;121 } else {122 tagsString += "," + tags[i].tagTitle;123 }124 }125 $("#tag").val(tagsString);126 $("#permalink").val(result.article.articlePermalink);127 $("#viewPwd").val(result.article.articleViewPwd);128 $("#articleCommentable").prop("checked", result.article.articleCommentable);129 // signs130 var signs = result.article.signs;131 $(".signs button").each(function (i) {132 if (parseInt(result.article.articleSignId) === parseInt(signs[i].oId)) {133 $("#articleSign" + signs[i].oId).addClass("selected");134 } else {135 $("#articleSign" + signs[i].oId).removeClass("selected");136 }137 });138 admin.article.setStatus();139 $("#loadMsg").text("");140 }141 });142 },143 /**144 * @description 删除文章145 * @param {String} id 文章 id146 * @param {String} fromId 文章来自草稿夹(draft)/文件夹(article)147 * @param {String} title 文章标题148 */149 del: function (id, fromId, title) {150 var isDelete = confirm(Label.confirmRemoveLabel + Label.articleLabel + '"' + title + '"?');151 if (isDelete) {152 $("#loadMsg").text(Label.loadingLabel);153 $("#tipMsg").text("");154 $.ajax({155 url: latkeConfig.servePath + "/console/article/" + id,156 type: "DELETE",157 cache: false,158 success: function (result, textStatus) {159 $("#tipMsg").text(result.msg);160 if (!result.sc) {161 $("#loadMsg").text("");162 return;163 }164 admin[fromId + "List"].getList(1);165 }166 });167 }168 },169 /**170 * @@description 添加文章171 * @param {Boolean} articleIsPublished 文章是否发布过172 * @param {Boolean} isAuto 是否为自动保存173 */174 add: function (articleIsPublished, isAuto) {175 if (admin.article.validate()) {176 var that = this;177 that._addDisabled();178 $("#loadMsg").text(Label.loadingLabel);179 $("#tipMsg").text("");180 var signId = "";181 $(".signs button").each(function () {182 if (this.className === "selected") {183 signId = this.id.substr(this.id.length - 1, 1);184 }185 });186 var articleContent = admin.editors.articleEditor.getContent(),187 articleAbstract = admin.editors.abstractEditor.getContent();188 if ($('#articleThumbnail').prop('checked')) {189 var bgImage = $('.thumbnail__img').css('background-image');190 articleContent = '![](' + bgImage.substring(5, bgImage.length - 2) + ')\n\n' + articleContent;191 }192 var requestJSONObject = {193 "article": {194 "articleTitle": $("#title").val(),195 "articleContent": articleContent,196 "articleAbstract": articleAbstract,197 "articleTags": this.trimUniqueArray($("#tag").val()).toString(),198 "articlePermalink": $("#permalink").val(),199 "articleIsPublished": articleIsPublished,200 "articleSignId": signId,201 "postToCommunity": $("#postToCommunity").prop("checked"),202 "articleCommentable": $("#articleCommentable").prop("checked"),203 "articleViewPwd": $("#viewPwd").val()204 }205 };206 $.ajax({207 url: latkeConfig.servePath + "/console/article/",208 type: "POST",209 cache: false,210 data: JSON.stringify(requestJSONObject),211 success: function (result, textStatus) {212 if (isAuto) {213 $("#tipMsg").text(Label.autoSaveLabel);214 admin.article.status.id = result.oId;215 return;216 }217 $("#tipMsg").text(result.msg);218 if (!result.sc) {219 return;220 }221 if (articleIsPublished) {222 admin.article.status.id = undefined;223 admin.selectTab("article/article-list");224 } else {225 admin.selectTab("article/draft-list");226 }227 admin.article.isConfirm = false;228 },229 complete: function (jqXHR, textStatus) {230 that._removeDisabled();231 $("#loadMsg").text("");232 if (jqXHR.status === 403) {233 $.get("/admin-index.do");234 that.add(articleIsPublished);235 }236 }237 });238 }239 },240 /**241 * @description 更新文章242 * @param {Boolean} articleIsPublished 文章是否发布过243 * @param {Boolean} isAuto 是否为自动保存244 */245 update: function (articleIsPublished, isAuto) {246 if (admin.article.validate()) {247 var that = this;248 that._addDisabled();249 $("#loadMsg").text(Label.loadingLabel);250 $("#tipMsg").text("");251 var signId = "";252 $(".signs button").each(function () {253 if (this.className === "selected") {254 signId = this.id.substr(this.id.length - 1, 1);255 }256 });257 var articleContent = admin.editors.articleEditor.getContent(),258 articleAbstract = admin.editors.abstractEditor.getContent();259 if ($('#articleThumbnail').prop('checked')) {260 var bgImage = $('.thumbnail__img').css('background-image');261 articleContent = '![](' + bgImage.substring(5, bgImage.length - 2) + ') \n\n' + articleContent;262 }263 var requestJSONObject = {264 "article": {265 "oId": this.status.id,266 "articleTitle": $("#title").val(),267 "articleContent": articleContent,268 "articleAbstract": articleAbstract,269 "articleTags": this.trimUniqueArray($("#tag").val()).toString(),270 "articlePermalink": $("#permalink").val(),271 "articleIsPublished": articleIsPublished,272 "articleSignId": signId,273 "articleCommentable": $("#articleCommentable").prop("checked"),274 "articleViewPwd": $("#viewPwd").val(),275 "postToCommunity": $("#postToCommunity").prop("checked"),276 "articleEditorType": admin.article.currentEditorType277 }278 };279 $.ajax({280 url: latkeConfig.servePath + "/console/article/",281 type: "PUT",282 cache: false,283 data: JSON.stringify(requestJSONObject),284 success: function (result, textStatus) {285 if (isAuto) {286 $("#tipMsg").text(Label.autoSaveLabel);287 return;288 }289 $("#tipMsg").text(result.msg);290 if (!result.sc) {291 return;292 }293 if (articleIsPublished) {294 admin.selectTab("article/article-list");295 } else {296 admin.selectTab("article/draft-list");297 }298 $("#tipMsg").text(Label.updateSuccLabel);299 admin.article.status.id = undefined;300 admin.article.isConfirm = false;301 },302 complete: function (jqXHR, textStatus) {303 that._removeDisabled();304 $("#loadMsg").text("");305 if (jqXHR.status === 403) {306 $.get("/admin-index.do");307 that.update(articleIsPublished);308 }309 }310 });311 }312 },313 /**314 * @description 发布文章页面设置文章按钮、发布到社区等状态的显示315 */316 setStatus: function () {317 $.ajax({// Gets all tags318 url: latkeConfig.servePath + "/console/tags",319 type: "GET",320 cache: false,321 success: function (result, textStatus) {322 $("#tipMsg").text(result.msg);323 if (!result.sc) {324 $("#loadMsg").text("");325 return;326 }327 if (0 >= result.tags.length) {328 return;329 }330 $("#tagCheckboxPanel>span").remove("");331 var spans = "";332 for (var i = 0; i < result.tags.length; i++) {333 spans += "<span>" + result.tags[i].tagTitle + "</span>";334 }335 $("#tagCheckboxPanel").html(spans + '<div class="clear"></div>');336 $("#loadMsg").text("");337 }338 });339 // set button status340 if (this.status) {341 if (this.status.isArticle) {342 $("#unSubmitArticle").show();343 $("#saveArticle").hide();344 $("#submitArticle").show();345 } else {346 $("#submitArticle").show();347 $("#unSubmitArticle").hide();348 $("#saveArticle").show();349 }350 if (this.status.articleHadBeenPublished) {351 $("#postToCommunityPanel").hide();352 } else {353 // 1.0.0 开始默认会发布到社区354 // $("#postToCommunityPanel").show();355 }356 } else {357 $("#submitArticle").show();358 $("#unSubmitArticle").hide();359 $("#saveArticle").show();360 // 1.0.0 开始默认会发布到社区361 // $("#postToCommunityPanel").show();362 }363 $("#postToCommunity").attr("checked", "checked");364 },365 /**366 * @description 清除发布文章页面的输入框的内容367 */368 clear: function () {369 this.status = {370 id: undefined,371 isArticle: undefined,372 articleHadBeenPublished: undefined373 };374 this.setStatus();375 $("#title").val("");376 admin.editors.articleEditor.setContent("");377 admin.editors.abstractEditor.setContent("");378 // reset tag379 $("#tag").val("");380 $("#tagCheckboxPanel").hide().find("span").removeClass("selected");381 $("#permalink").val("");382 $("#articleCammentable").prop("checked", true);383 $("#postToCommunity").prop("checked", true);384 $(".signs button").each(function (i) {385 if (i === 0) {386 this.className = "selected";387 } else {388 this.className = "";389 }390 });391 $(".editor-preview-active").html("").removeClass('editor-preview-active');392 $("#uploadContent").remove();393 if ($('#articleThumbnail').prop('checked')) {394 $('#articleThumbnail').click();395 }396 },397 /**398 * @description 初始化发布文章页面399 * @param {Function} fun 切面函数400 */401 init: function (fun) {402 this.currentEditorType = Label.editorType;403 // Inits Signs.404 $(".signs button").click(function (i) {405 $(".signs button").removeClass('selected');406 $(this).addClass('selected');407 });408 // For tag auto-completion409 $.ajax({// Gets all tags410 url: latkeConfig.servePath + "/console/tags",411 type: "GET",412 cache: false,413 success: function (result, textStatus) {414 $("#tipMsg").text(result.msg);415 if (!result.sc) {416 $("#loadMsg").text("");417 return;418 }419 if (0 >= result.tags.length) {420 return;421 }422 var tags = [];423 for (var i = 0; i < result.tags.length; i++) {424 tags.push(result.tags[i].tagTitle);425 }426 $("#tag").completed({427 height: 160,428 buttonText: Label.selectLabel,429 data: tags430 }).innerWidth($("#tag").parent().width() - 68);431 $("#loadMsg").text("");432 }433 });434 // submit action435 $("#submitArticle").click(function () {436 if (admin.article.status.id) {437 admin.article.update(true);438 } else {439 admin.article.add(true);440 }441 });442 $("#saveArticle").click(function () {443 if (admin.article.status.id) {444 admin.article.update(admin.article.status.isArticle);445 } else {446 admin.article.add(false);447 }448 });449 this.initUploadFile('articleUpload');450 // editor451 admin.editors.articleEditor = new SoloEditor({452 id: "articleContent",453 kind: "all",454 fun: fun,455 height: 500456 });457 admin.editors.abstractEditor = new SoloEditor({458 id: "abstract",459 kind: "simple",460 height: 200461 });462 admin.article.clearDraftTimer();463 admin.article.autoSaveDraftTimer = setInterval(function () {464 admin.article._autoSaveToDraft();465 }, admin.article.AUTOSAVETIME);466 // thumbnail467 $('#articleThumbnailBtn').click(function () {468 $.ajax({// Gets all tags469 url: latkeConfig.servePath + "/console/thumbs?n=1",470 type: "GET",471 cache: false,472 success: function (result, textStatus) {473 if (!result.sc) {474 $("#loadMsg").text(result.msg);475 return;476 }477 $('#articleThumbnailBtn').prev().css('background-image', 'url(' + result.data[0] + ')');478 }479 });480 }).click();481 },482 /**483 * @description 自动保存草稿件484 */485 _autoSaveToDraft: function () {486 if ($("#title").val().replace(/\s/g, "") === "" ||487 admin.editors.articleEditor.getContent().replace(/\s/g, "") === "" ||488 $("#tag").val().replace(/\s/g, "") === "") {489 return;490 }491 if (admin.article.status.id) {492 if (!admin.article.status.isArticle) {493 admin.article.update(false, true);494 }495 } else {496 admin.article.add(false, true);497 admin.article.status.isArticle = false;498 }499 },500 /**501 * @description 关闭定时器502 */503 clearDraftTimer: function () {504 if (admin.article.autoSaveDraftTimer !== "") {505 window.clearInterval(admin.article.autoSaveDraftTimer);506 admin.article.autoSaveDraftTimer = "";507 }508 },509 /**510 * @description 验证发布文章字段的合法性511 */512 validate: function () {513 var articleContent = admin.editors.articleEditor.getContent();514 if ($("#title").val().replace(/\s/g, "") === "") {515 $("#tipMsg").text(Label.titleEmptyLabel);516 $("#title").focus().val("");517 } else if (articleContent.replace(/\s/g, "") === "") {518 $("#tipMsg").text(Label.contentEmptyLabel);519 } else if ($("#tag").val().replace(/\s/g, "") === "") {520 $("#tipMsg").text(Label.tagsEmptyLabel);521 $("#tag").focus().val("");522 } else {523 return true;524 }525 return false;526 },527 /**528 * @description 取消发布 529 * @param {Boolean} isAuto 是否为自动保存530 */531 unPublish: function (isAuto) {532 var that = this;533 that._addDisabled();534 $.ajax({535 url: latkeConfig.servePath + "/console/article/unpublish/" + admin.article.status.id,536 type: "PUT",537 cache: false,538 success: function (result, textStatus) {539 if (isAuto) {540 $("#tipMsg").text(Label.autoSaveLabel);541 return;542 }543 $("#tipMsg").text(result.msg);544 if (!result.sc) {545 return;546 }547 admin.selectTab("article/draft-list");548 admin.article.status.id = undefined;549 admin.article.isConfirm = false;550 },551 complete: function (jqXHR, textStatus) {552 that._removeDisabled();553 $("#loadMsg").text("");554 if (jqXHR.status === 403) {555 $.get("/admin-index.do");556 that.unPublish();557 }558 }559 });560 },561 /**562 * @description 数组中无重复563 * @param {String} str 被解析的字符串564 * @returns {String} 无重复的字符串565 */566 trimUniqueArray: function (str) {567 str = str.toString();568 var arr = str.split(",");569 for (var i = 0; i < arr.length; i++) {570 arr[i] = arr[i].replace(/(^\s*)|(\s*$)/g, "");571 if (arr[i] === "") {572 arr.splice(i, 1);573 i--;574 }575 }576 var unique = $.unique(arr);577 return unique.toString();578 },579 /**580 * @description 点击发文文章时的处理581 */582 prePost: function () {583 $("#loadMsg").text(Label.loadingLabel);584 admin.article.content = "";585 if (!admin.editors.articleEditor.getContent) {586 return;587 }588 var articleContent = admin.editors.articleEditor.getContent();589 if (window.location.hash === "#article/article" &&590 articleContent.replace(/\s/g, '') !== "") {591 if (confirm(Label.editorPostLabel)) {592 admin.article.clear();593 }594 }595 $("#tipMsg").text("");596 $("#loadMsg").text("");597 if (admin.article.currentEditorType !== Label.editorType) {598 admin.editors.articleEditor.remove();599 admin.editors.abstractEditor.remove();600 admin.article.currentEditorType = Label.editorType;601 admin.editors.articleEditor.init(Label.editorType);602 admin.editors.abstractEditor.init(Label.editorType);603 }604 },605 /**606 * @description: 仿重复提交,点击一次后,按钮设置为 disabled607 */608 _addDisabled: function () {609 $("#unSubmitArticle").attr("disabled", "disabled");610 $("#saveArticle").attr("disabled", "disabled");611 $("#submitArticle").attr("disabled", "disabled");612 },613 /**614 * @description: 仿重复提交,当后台有数据返回后,按钮移除 disabled 状态615 */616 _removeDisabled: function () {617 $("#unSubmitArticle").removeAttr("disabled");618 $("#saveArticle").removeAttr("disabled");619 $("#submitArticle").removeAttr("disabled");620 }621};622/**623 * @description 注册到 admin 进行管理 624 */625admin.register.article = {626 "obj": admin.article,627 "init": admin.article.init,628 "refresh": function () {629 admin.editors.abstractEditor.setContent('');630 admin.editors.articleEditor.setContent('');631 $("#loadMsg").text("");632 $("#tipMsg").text("");633 }634};635function getUUID() {636 var d = new Date().getTime();637 var ret = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {638 var r = (d + Math.random() * 16) % 16 | 0;639 d = Math.floor(d / 16);640 return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);641 });642 ret = ret.replace(new RegExp("-", 'g'), "");643 return ret;644}...

Full Screen

Full Screen

tests.py

Source:tests.py Github

copy

Full Screen

1from datetime import datetime2from operator import attrgetter3from django.conf import settings4from django.core.exceptions import FieldError5from django.db import connection, DEFAULT_DB_ALIAS6from django.test import TestCase7from models import Article8class LookupTests(TestCase):9 #def setUp(self):10 def setUp(self):11 # Create a couple of Articles.12 self.a1 = Article(headline='Article 1', pub_date=datetime(2005, 7, 26))13 self.a1.save()14 self.a2 = Article(headline='Article 2', pub_date=datetime(2005, 7, 27))15 self.a2.save()16 self.a3 = Article(headline='Article 3', pub_date=datetime(2005, 7, 27))17 self.a3.save()18 self.a4 = Article(headline='Article 4', pub_date=datetime(2005, 7, 28))19 self.a4.save()20 self.a5 = Article(headline='Article 5', pub_date=datetime(2005, 8, 1, 9, 0))21 self.a5.save()22 self.a6 = Article(headline='Article 6', pub_date=datetime(2005, 8, 1, 8, 0))23 self.a6.save()24 self.a7 = Article(headline='Article 7', pub_date=datetime(2005, 7, 27))25 self.a7.save()26 def test_exists(self):27 # We can use .exists() to check that there are some28 self.assertTrue(Article.objects.exists())29 for a in Article.objects.all():30 a.delete()31 # There should be none now!32 self.assertFalse(Article.objects.exists())33 def test_lookup_int_as_str(self):34 # Integer value can be queried using string35 self.assertQuerysetEqual(Article.objects.filter(id__iexact=str(self.a1.id)),36 ['<Article: Article 1>'])37 if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] in (38 'django.db.backends.postgresql',39 'django.db.backends.postgresql_psycopg2'):40 def test_lookup_date_as_str(self):41 # A date lookup can be performed using a string search42 self.assertQuerysetEqual(Article.objects.filter(pub_date__startswith='2005'),43 [44 '<Article: Article 5>',45 '<Article: Article 6>',46 '<Article: Article 4>',47 '<Article: Article 2>',48 '<Article: Article 3>',49 '<Article: Article 7>',50 '<Article: Article 1>',51 ])52 def test_iterator(self):53 # Each QuerySet gets iterator(), which is a generator that "lazily"54 # returns results using database-level iteration.55 self.assertQuerysetEqual(Article.objects.iterator(),56 [57 'Article 5',58 'Article 6',59 'Article 4',60 'Article 2',61 'Article 3',62 'Article 7',63 'Article 1',64 ],65 transform=attrgetter('headline'))66 # iterator() can be used on any QuerySet.67 self.assertQuerysetEqual(68 Article.objects.filter(headline__endswith='4').iterator(),69 ['Article 4'],70 transform=attrgetter('headline'))71 def test_count(self):72 # count() returns the number of objects matching search criteria.73 self.assertEqual(Article.objects.count(), 7)74 self.assertEqual(Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).count(), 3)75 self.assertEqual(Article.objects.filter(headline__startswith='Blah blah').count(), 0)76 # count() should respect sliced query sets.77 articles = Article.objects.all()78 self.assertEqual(articles.count(), 7)79 self.assertEqual(articles[:4].count(), 4)80 self.assertEqual(articles[1:100].count(), 6)81 self.assertEqual(articles[10:100].count(), 0)82 # Date and date/time lookups can also be done with strings.83 self.assertEqual(Article.objects.filter(pub_date__exact='2005-07-27 00:00:00').count(), 3)84 def test_in_bulk(self):85 # in_bulk() takes a list of IDs and returns a dictionary mapping IDs to objects.86 arts = Article.objects.in_bulk([self.a1.id, self.a2.id])87 self.assertEqual(arts[self.a1.id], self.a1)88 self.assertEqual(arts[self.a2.id], self.a2)89 self.assertEqual(Article.objects.in_bulk([self.a3.id]), {self.a3.id: self.a3})90 self.assertEqual(Article.objects.in_bulk(set([self.a3.id])), {self.a3.id: self.a3})91 self.assertEqual(Article.objects.in_bulk(frozenset([self.a3.id])), {self.a3.id: self.a3})92 self.assertEqual(Article.objects.in_bulk((self.a3.id,)), {self.a3.id: self.a3})93 self.assertEqual(Article.objects.in_bulk([1000]), {})94 self.assertEqual(Article.objects.in_bulk([]), {})95 self.assertRaises(AssertionError, Article.objects.in_bulk, 'foo')96 self.assertRaises(TypeError, Article.objects.in_bulk)97 self.assertRaises(TypeError, Article.objects.in_bulk, headline__startswith='Blah')98 def test_values(self):99 # values() returns a list of dictionaries instead of object instances --100 # and you can specify which fields you want to retrieve.101 identity = lambda x:x102 self.assertQuerysetEqual(Article.objects.values('headline'),103 [104 {'headline': u'Article 5'},105 {'headline': u'Article 6'},106 {'headline': u'Article 4'},107 {'headline': u'Article 2'},108 {'headline': u'Article 3'},109 {'headline': u'Article 7'},110 {'headline': u'Article 1'},111 ],112 transform=identity)113 self.assertQuerysetEqual(114 Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).values('id'),115 [{'id': self.a2.id}, {'id': self.a3.id}, {'id': self.a7.id}],116 transform=identity)117 self.assertQuerysetEqual(Article.objects.values('id', 'headline'),118 [119 {'id': self.a5.id, 'headline': 'Article 5'},120 {'id': self.a6.id, 'headline': 'Article 6'},121 {'id': self.a4.id, 'headline': 'Article 4'},122 {'id': self.a2.id, 'headline': 'Article 2'},123 {'id': self.a3.id, 'headline': 'Article 3'},124 {'id': self.a7.id, 'headline': 'Article 7'},125 {'id': self.a1.id, 'headline': 'Article 1'},126 ],127 transform=identity)128 # You can use values() with iterator() for memory savings,129 # because iterator() uses database-level iteration.130 self.assertQuerysetEqual(Article.objects.values('id', 'headline').iterator(),131 [132 {'headline': u'Article 5', 'id': self.a5.id},133 {'headline': u'Article 6', 'id': self.a6.id},134 {'headline': u'Article 4', 'id': self.a4.id},135 {'headline': u'Article 2', 'id': self.a2.id},136 {'headline': u'Article 3', 'id': self.a3.id},137 {'headline': u'Article 7', 'id': self.a7.id},138 {'headline': u'Article 1', 'id': self.a1.id},139 ],140 transform=identity)141 # The values() method works with "extra" fields specified in extra(select).142 self.assertQuerysetEqual(143 Article.objects.extra(select={'id_plus_one': 'id + 1'}).values('id', 'id_plus_one'),144 [145 {'id': self.a5.id, 'id_plus_one': self.a5.id + 1},146 {'id': self.a6.id, 'id_plus_one': self.a6.id + 1},147 {'id': self.a4.id, 'id_plus_one': self.a4.id + 1},148 {'id': self.a2.id, 'id_plus_one': self.a2.id + 1},149 {'id': self.a3.id, 'id_plus_one': self.a3.id + 1},150 {'id': self.a7.id, 'id_plus_one': self.a7.id + 1},151 {'id': self.a1.id, 'id_plus_one': self.a1.id + 1},152 ],153 transform=identity)154 data = {155 'id_plus_one': 'id+1',156 'id_plus_two': 'id+2',157 'id_plus_three': 'id+3',158 'id_plus_four': 'id+4',159 'id_plus_five': 'id+5',160 'id_plus_six': 'id+6',161 'id_plus_seven': 'id+7',162 'id_plus_eight': 'id+8',163 }164 self.assertQuerysetEqual(165 Article.objects.filter(id=self.a1.id).extra(select=data).values(*data.keys()),166 [{167 'id_plus_one': self.a1.id + 1,168 'id_plus_two': self.a1.id + 2,169 'id_plus_three': self.a1.id + 3,170 'id_plus_four': self.a1.id + 4,171 'id_plus_five': self.a1.id + 5,172 'id_plus_six': self.a1.id + 6,173 'id_plus_seven': self.a1.id + 7,174 'id_plus_eight': self.a1.id + 8,175 }], transform=identity)176 # However, an exception FieldDoesNotExist will be thrown if you specify177 # a non-existent field name in values() (a field that is neither in the178 # model nor in extra(select)).179 self.assertRaises(FieldError,180 Article.objects.extra(select={'id_plus_one': 'id + 1'}).values,181 'id', 'id_plus_two')182 # If you don't specify field names to values(), all are returned.183 self.assertQuerysetEqual(Article.objects.filter(id=self.a5.id).values(),184 [{185 'id': self.a5.id,186 'headline': 'Article 5',187 'pub_date': datetime(2005, 8, 1, 9, 0)188 }], transform=identity)189 def test_values_list(self):190 # values_list() is similar to values(), except that the results are191 # returned as a list of tuples, rather than a list of dictionaries.192 # Within each tuple, the order of the elemnts is the same as the order193 # of fields in the values_list() call.194 identity = lambda x:x195 self.assertQuerysetEqual(Article.objects.values_list('headline'),196 [197 (u'Article 5',),198 (u'Article 6',),199 (u'Article 4',),200 (u'Article 2',),201 (u'Article 3',),202 (u'Article 7',),203 (u'Article 1',),204 ], transform=identity)205 self.assertQuerysetEqual(Article.objects.values_list('id').order_by('id'),206 [(self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,)],207 transform=identity)208 self.assertQuerysetEqual(209 Article.objects.values_list('id', flat=True).order_by('id'),210 [self.a1.id, self.a2.id, self.a3.id, self.a4.id, self.a5.id, self.a6.id, self.a7.id],211 transform=identity)212 self.assertQuerysetEqual(213 Article.objects.extra(select={'id_plus_one': 'id+1'})214 .order_by('id').values_list('id'),215 [(self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,)],216 transform=identity)217 self.assertQuerysetEqual(218 Article.objects.extra(select={'id_plus_one': 'id+1'})219 .order_by('id').values_list('id_plus_one', 'id'),220 [221 (self.a1.id+1, self.a1.id),222 (self.a2.id+1, self.a2.id),223 (self.a3.id+1, self.a3.id),224 (self.a4.id+1, self.a4.id),225 (self.a5.id+1, self.a5.id),226 (self.a6.id+1, self.a6.id),227 (self.a7.id+1, self.a7.id)228 ],229 transform=identity)230 self.assertQuerysetEqual(231 Article.objects.extra(select={'id_plus_one': 'id+1'})232 .order_by('id').values_list('id', 'id_plus_one'),233 [234 (self.a1.id, self.a1.id+1),235 (self.a2.id, self.a2.id+1),236 (self.a3.id, self.a3.id+1),237 (self.a4.id, self.a4.id+1),238 (self.a5.id, self.a5.id+1),239 (self.a6.id, self.a6.id+1),240 (self.a7.id, self.a7.id+1)241 ],242 transform=identity)243 self.assertRaises(TypeError, Article.objects.values_list, 'id', 'headline', flat=True)244 def test_get_next_previous_by(self):245 # Every DateField and DateTimeField creates get_next_by_FOO() and246 # get_previous_by_FOO() methods. In the case of identical date values,247 # these methods will use the ID as a fallback check. This guarantees248 # that no records are skipped or duplicated.249 self.assertEqual(repr(self.a1.get_next_by_pub_date()),250 '<Article: Article 2>')251 self.assertEqual(repr(self.a2.get_next_by_pub_date()),252 '<Article: Article 3>')253 self.assertEqual(repr(self.a2.get_next_by_pub_date(headline__endswith='6')),254 '<Article: Article 6>')255 self.assertEqual(repr(self.a3.get_next_by_pub_date()),256 '<Article: Article 7>')257 self.assertEqual(repr(self.a4.get_next_by_pub_date()),258 '<Article: Article 6>')259 self.assertRaises(Article.DoesNotExist, self.a5.get_next_by_pub_date)260 self.assertEqual(repr(self.a6.get_next_by_pub_date()),261 '<Article: Article 5>')262 self.assertEqual(repr(self.a7.get_next_by_pub_date()),263 '<Article: Article 4>')264 self.assertEqual(repr(self.a7.get_previous_by_pub_date()),265 '<Article: Article 3>')266 self.assertEqual(repr(self.a6.get_previous_by_pub_date()),267 '<Article: Article 4>')268 self.assertEqual(repr(self.a5.get_previous_by_pub_date()),269 '<Article: Article 6>')270 self.assertEqual(repr(self.a4.get_previous_by_pub_date()),271 '<Article: Article 7>')272 self.assertEqual(repr(self.a3.get_previous_by_pub_date()),273 '<Article: Article 2>')274 self.assertEqual(repr(self.a2.get_previous_by_pub_date()),275 '<Article: Article 1>')276 def test_escaping(self):277 # Underscores, percent signs and backslashes have special meaning in the278 # underlying SQL code, but Django handles the quoting of them automatically.279 a8 = Article(headline='Article_ with underscore', pub_date=datetime(2005, 11, 20))280 a8.save()281 self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article'),282 [283 '<Article: Article_ with underscore>',284 '<Article: Article 5>',285 '<Article: Article 6>',286 '<Article: Article 4>',287 '<Article: Article 2>',288 '<Article: Article 3>',289 '<Article: Article 7>',290 '<Article: Article 1>',291 ])292 self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article_'),293 ['<Article: Article_ with underscore>'])294 a9 = Article(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21))295 a9.save()296 self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article'),297 [298 '<Article: Article% with percent sign>',299 '<Article: Article_ with underscore>',300 '<Article: Article 5>',301 '<Article: Article 6>',302 '<Article: Article 4>',303 '<Article: Article 2>',304 '<Article: Article 3>',305 '<Article: Article 7>',306 '<Article: Article 1>',307 ])308 self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article%'),309 ['<Article: Article% with percent sign>'])310 a10 = Article(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22))311 a10.save()312 self.assertQuerysetEqual(Article.objects.filter(headline__contains='\\'),313 ['<Article: Article with \ backslash>'])314 def test_exclude(self):315 a8 = Article.objects.create(headline='Article_ with underscore', pub_date=datetime(2005, 11, 20))316 a9 = Article.objects.create(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21))317 a10 = Article.objects.create(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22))318 # exclude() is the opposite of filter() when doing lookups:319 self.assertQuerysetEqual(320 Article.objects.filter(headline__contains='Article').exclude(headline__contains='with'),321 [322 '<Article: Article 5>',323 '<Article: Article 6>',324 '<Article: Article 4>',325 '<Article: Article 2>',326 '<Article: Article 3>',327 '<Article: Article 7>',328 '<Article: Article 1>',329 ])330 self.assertQuerysetEqual(Article.objects.exclude(headline__startswith="Article_"),331 [332 '<Article: Article with \\ backslash>',333 '<Article: Article% with percent sign>',334 '<Article: Article 5>',335 '<Article: Article 6>',336 '<Article: Article 4>',337 '<Article: Article 2>',338 '<Article: Article 3>',339 '<Article: Article 7>',340 '<Article: Article 1>',341 ])342 self.assertQuerysetEqual(Article.objects.exclude(headline="Article 7"),343 [344 '<Article: Article with \\ backslash>',345 '<Article: Article% with percent sign>',346 '<Article: Article_ with underscore>',347 '<Article: Article 5>',348 '<Article: Article 6>',349 '<Article: Article 4>',350 '<Article: Article 2>',351 '<Article: Article 3>',352 '<Article: Article 1>',353 ])354 def test_none(self):355 # none() returns an EmptyQuerySet that behaves like any other QuerySet object356 self.assertQuerysetEqual(Article.objects.none(), [])357 self.assertQuerysetEqual(358 Article.objects.none().filter(headline__startswith='Article'), [])359 self.assertQuerysetEqual(360 Article.objects.filter(headline__startswith='Article').none(), [])361 self.assertEqual(Article.objects.none().count(), 0)362 self.assertEqual(363 Article.objects.none().update(headline="This should not take effect"), 0)364 self.assertQuerysetEqual(365 [article for article in Article.objects.none().iterator()],366 [])367 def test_in(self):368 # using __in with an empty list should return an empty query set369 self.assertQuerysetEqual(Article.objects.filter(id__in=[]), [])370 self.assertQuerysetEqual(Article.objects.exclude(id__in=[]),371 [372 '<Article: Article 5>',373 '<Article: Article 6>',374 '<Article: Article 4>',375 '<Article: Article 2>',376 '<Article: Article 3>',377 '<Article: Article 7>',378 '<Article: Article 1>',379 ])380 def test_error_messages(self):381 # Programming errors are pointed out with nice error messages382 try:383 Article.objects.filter(pub_date_year='2005').count()384 self.fail('FieldError not raised')385 except FieldError, ex:386 self.assertEqual(str(ex), "Cannot resolve keyword 'pub_date_year' "387 "into field. Choices are: headline, id, pub_date")388 try:389 Article.objects.filter(headline__starts='Article')390 self.fail('FieldError not raised')391 except FieldError, ex:392 self.assertEqual(str(ex), "Join on field 'headline' not permitted. "393 "Did you misspell 'starts' for the lookup type?")394 def test_regex(self):395 # Create some articles with a bit more interesting headlines for testing field lookups:396 for a in Article.objects.all():397 a.delete()398 now = datetime.now()399 a1 = Article(pub_date=now, headline='f')400 a1.save()401 a2 = Article(pub_date=now, headline='fo')402 a2.save()403 a3 = Article(pub_date=now, headline='foo')404 a3.save()405 a4 = Article(pub_date=now, headline='fooo')406 a4.save()407 a5 = Article(pub_date=now, headline='hey-Foo')408 a5.save()409 a6 = Article(pub_date=now, headline='bar')410 a6.save()411 a7 = Article(pub_date=now, headline='AbBa')412 a7.save()413 a8 = Article(pub_date=now, headline='baz')414 a8.save()415 a9 = Article(pub_date=now, headline='baxZ')416 a9.save()417 # zero-or-more418 self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'fo*'),419 ['<Article: f>', '<Article: fo>', '<Article: foo>', '<Article: fooo>'])420 self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'fo*'),421 [422 '<Article: f>',423 '<Article: fo>',424 '<Article: foo>',425 '<Article: fooo>',426 '<Article: hey-Foo>',427 ])428 # one-or-more429 self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'fo+'),430 ['<Article: fo>', '<Article: foo>', '<Article: fooo>'])431 # wildcard432 self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'fooo?'),433 ['<Article: foo>', '<Article: fooo>'])434 # leading anchor435 self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'^b'),436 ['<Article: bar>', '<Article: baxZ>', '<Article: baz>'])437 self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'^a'),438 ['<Article: AbBa>'])439 # trailing anchor440 self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'z$'),441 ['<Article: baz>'])442 self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'z$'),443 ['<Article: baxZ>', '<Article: baz>'])444 # character sets445 self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'ba[rz]'),446 ['<Article: bar>', '<Article: baz>'])447 self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'ba.[RxZ]'),448 ['<Article: baxZ>'])449 self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'ba[RxZ]'),450 ['<Article: bar>', '<Article: baxZ>', '<Article: baz>'])451 # and more articles:452 a10 = Article(pub_date=now, headline='foobar')453 a10.save()454 a11 = Article(pub_date=now, headline='foobaz')455 a11.save()456 a12 = Article(pub_date=now, headline='ooF')457 a12.save()458 a13 = Article(pub_date=now, headline='foobarbaz')459 a13.save()460 a14 = Article(pub_date=now, headline='zoocarfaz')461 a14.save()462 a15 = Article(pub_date=now, headline='barfoobaz')463 a15.save()464 a16 = Article(pub_date=now, headline='bazbaRFOO')465 a16.save()466 # alternation467 self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'oo(f|b)'),468 [469 '<Article: barfoobaz>',470 '<Article: foobar>',471 '<Article: foobarbaz>',472 '<Article: foobaz>',473 ])474 self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'oo(f|b)'),475 [476 '<Article: barfoobaz>',477 '<Article: foobar>',478 '<Article: foobarbaz>',479 '<Article: foobaz>',480 '<Article: ooF>',481 ])482 self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'^foo(f|b)'),483 ['<Article: foobar>', '<Article: foobarbaz>', '<Article: foobaz>'])484 # greedy matching485 self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'b.*az'),486 [487 '<Article: barfoobaz>',488 '<Article: baz>',489 '<Article: bazbaRFOO>',490 '<Article: foobarbaz>',491 '<Article: foobaz>',492 ])493 self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'b.*ar'),494 [495 '<Article: bar>',496 '<Article: barfoobaz>',497 '<Article: bazbaRFOO>',498 '<Article: foobar>',499 '<Article: foobarbaz>',500 ])501 if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.mysql':502 def test_regex_backreferencing(self):503 # grouping and backreferences504 now = datetime.now()505 a10 = Article(pub_date=now, headline='foobar')506 a10.save()507 a11 = Article(pub_date=now, headline='foobaz')508 a11.save()509 a12 = Article(pub_date=now, headline='ooF')510 a12.save()511 a13 = Article(pub_date=now, headline='foobarbaz')512 a13.save()513 a14 = Article(pub_date=now, headline='zoocarfaz')514 a14.save()515 a15 = Article(pub_date=now, headline='barfoobaz')516 a15.save()517 a16 = Article(pub_date=now, headline='bazbaRFOO')518 a16.save()519 self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'b(.).*b\1'),...

Full Screen

Full Screen

content.py

Source:content.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2"""\3This is a python port of "Goose" orignialy licensed to Gravity.com4under one or more contributor license agreements. See the NOTICE file5distributed with this work for additional information6regarding copyright ownership.7Python port was written by Xavier Grangier for Recrutae8Gravity.com licenses this file9to you under the Apache License, Version 2.0 (the "License");10you may not use this file except in compliance11with the License. You may obtain a copy of the License at12http://www.apache.org/licenses/LICENSE-2.013Unless required by applicable law or agreed to in writing, software14distributed under the License is distributed on an "AS IS" BASIS,15WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.16See the License for the specific language governing permissions and17limitations under the License.18"""19from base import TestExtractionBase20from goose.text import StopWordsChinese21from goose.text import StopWordsArabic22from goose.text import StopWordsKorean23class TestExtractions(TestExtractionBase):24 def test_allnewlyrics1(self):25 article = self.getArticle()26 fields = ['title', 'cleaned_text']27 self.runArticleAssertions(article=article, fields=fields)28 def test_cnn1(self):29 article = self.getArticle()30 fields = ['title', 'cleaned_text']31 self.runArticleAssertions(article=article, fields=fields)32 def test_businessWeek1(self):33 article = self.getArticle()34 fields = ['title', 'cleaned_text']35 self.runArticleAssertions(article=article, fields=fields)36 def test_businessWeek2(self):37 article = self.getArticle()38 fields = ['title', 'cleaned_text']39 self.runArticleAssertions(article=article, fields=fields)40 def test_businessWeek3(self):41 article = self.getArticle()42 fields = ['cleaned_text']43 self.runArticleAssertions(article=article, fields=fields)44 def test_cbslocal(self):45 article = self.getArticle()46 fields = ['cleaned_text']47 self.runArticleAssertions(article=article, fields=fields)48 def test_elmondo1(self):49 article = self.getArticle()50 fields = ['cleaned_text']51 self.runArticleAssertions(article=article, fields=fields)52 def test_elpais(self):53 article = self.getArticle()54 fields = ['cleaned_text']55 self.runArticleAssertions(article=article, fields=fields)56 def test_liberation(self):57 article = self.getArticle()58 fields = ['cleaned_text']59 self.runArticleAssertions(article=article, fields=fields)60 def test_lefigaro(self):61 article = self.getArticle()62 fields = ['cleaned_text']63 self.runArticleAssertions(article=article, fields=fields)64 def test_techcrunch1(self):65 article = self.getArticle()66 fields = ['title', 'cleaned_text']67 self.runArticleAssertions(article=article, fields=fields)68 def test_foxNews(self):69 article = self.getArticle()70 fields = ['cleaned_text']71 self.runArticleAssertions(article=article, fields=fields)72 def test_aolNews(self):73 article = self.getArticle()74 fields = ['cleaned_text']75 self.runArticleAssertions(article=article, fields=fields)76 def test_huffingtonPost2(self):77 article = self.getArticle()78 fields = ['cleaned_text']79 self.runArticleAssertions(article=article, fields=fields)80 def test_testHuffingtonPost(self):81 article = self.getArticle()82 fields = ['cleaned_text', 'meta_description', 'title', ]83 self.runArticleAssertions(article=article, fields=fields)84 def test_espn(self):85 article = self.getArticle()86 fields = ['cleaned_text']87 self.runArticleAssertions(article=article, fields=fields)88 def test_engadget(self):89 article = self.getArticle()90 fields = ['cleaned_text']91 self.runArticleAssertions(article=article, fields=fields)92 def test_msn1(self):93 article = self.getArticle()94 fields = ['cleaned_text']95 self.runArticleAssertions(article=article, fields=fields)96 # #########################################97 # # FAIL CHECK98 # # UNICODE99 # def test_guardian1(self):100 # article = self.getArticle()101 # fields = ['cleaned_text']102 # self.runArticleAssertions(article=article, fields=fields)103 def test_time(self):104 article = self.getArticle()105 fields = ['cleaned_text', 'title']106 self.runArticleAssertions(article=article, fields=fields)107 def test_time2(self):108 article = self.getArticle()109 fields = ['cleaned_text']110 self.runArticleAssertions(article=article, fields=fields)111 def test_cnet(self):112 article = self.getArticle()113 fields = ['cleaned_text']114 self.runArticleAssertions(article=article, fields=fields)115 def test_yahoo(self):116 article = self.getArticle()117 fields = ['cleaned_text']118 self.runArticleAssertions(article=article, fields=fields)119 def test_politico(self):120 article = self.getArticle()121 fields = ['cleaned_text']122 self.runArticleAssertions(article=article, fields=fields)123 def test_businessinsider3(self):124 article = self.getArticle()125 fields = ['cleaned_text']126 self.runArticleAssertions(article=article, fields=fields)127 def test_cnbc1(self):128 article = self.getArticle()129 fields = ['cleaned_text']130 self.runArticleAssertions(article=article, fields=fields)131 def test_marketplace(self):132 article = self.getArticle()133 fields = ['cleaned_text']134 self.runArticleAssertions(article=article, fields=fields)135 def test_issue24(self):136 article = self.getArticle()137 fields = ['cleaned_text']138 self.runArticleAssertions(article=article, fields=fields)139 def test_issue25(self):140 article = self.getArticle()141 fields = ['cleaned_text']142 self.runArticleAssertions(article=article, fields=fields)143 def test_issue28(self):144 article = self.getArticle()145 fields = ['cleaned_text']146 self.runArticleAssertions(article=article, fields=fields)147 def test_issue32(self):148 article = self.getArticle()149 fields = ['cleaned_text']150 self.runArticleAssertions(article=article, fields=fields)151 def test_issue4(self):152 article = self.getArticle()153 fields = ['cleaned_text']154 self.runArticleAssertions(article=article, fields=fields)155 def test_gizmodo1(self):156 article = self.getArticle()157 fields = ['cleaned_text', 'meta_description', 'meta_keywords']158 self.runArticleAssertions(article=article, fields=fields)159 def test_mashable_issue_74(self):160 article = self.getArticle()161 fields = ['cleaned_text']162 self.runArticleAssertions(article=article, fields=fields)163 def test_usatoday_issue_74(self):164 article = self.getArticle()165 fields = ['cleaned_text']166 self.runArticleAssertions(article=article, fields=fields)167 def test_okaymarketing(self):168 article = self.getArticle()169 fields = ['cleaned_text']170 self.runArticleAssertions(article=article, fields=fields)171 def test_issue129(self):172 article = self.getArticle()173 fields = ['cleaned_text']174 self.runArticleAssertions(article=article, fields=fields)175 def test_issue115(self):176 # https://github.com/grangier/python-goose/issues/115177 article = self.getArticle()178 fields = ['cleaned_text']179 self.runArticleAssertions(article=article, fields=fields)180class TestArticleTopNode(TestExtractionBase):181 def test_articlebody_itemprop(self):182 article = self.getArticle()183 fields = ['cleaned_text']184 self.runArticleAssertions(article=article, fields=fields)185 def test_articlebody_attribute(self):186 article = self.getArticle()187 fields = ['cleaned_text']188 self.runArticleAssertions(article=article, fields=fields)189 def test_articlebody_tag(self):190 article = self.getArticle()191 fields = ['cleaned_text']192 self.runArticleAssertions(article=article, fields=fields)193class TestExtractWithUrl(TestExtractionBase):194 def test_get_canonical_url(self):195 article = self.getArticle()196 fields = ['cleaned_text', 'canonical_link']197 self.runArticleAssertions(article=article, fields=fields)198class TestExtractChinese(TestExtractionBase):199 def getConfig(self):200 config = super(TestExtractChinese, self).getConfig()201 config.stopwords_class = StopWordsChinese202 return config203 def test_bbc_chinese(self):204 article = self.getArticle()205 fields = ['cleaned_text']206 self.runArticleAssertions(article=article, fields=fields)207class TestExtractArabic(TestExtractionBase):208 def getConfig(self):209 config = super(TestExtractArabic, self).getConfig()210 config.stopwords_class = StopWordsArabic211 return config212 def test_cnn_arabic(self):213 article = self.getArticle()214 fields = ['cleaned_text']215 self.runArticleAssertions(article=article, fields=fields)216class TestExtractKorean(TestExtractionBase):217 def getConfig(self):218 config = super(TestExtractKorean, self).getConfig()219 config.stopwords_class = StopWordsKorean220 return config221 def test_donga_korean(self):222 article = self.getArticle()223 fields = ['cleaned_text', 'meta_description', 'meta_keywords']224 self.runArticleAssertions(article=article, fields=fields)225class TestExtractionsRaw(TestExtractions):226 def extract(self, instance):227 article = instance.extract(raw_html=self.getRawHtml())...

Full Screen

Full Screen

create_update.py

Source:create_update.py Github

copy

Full Screen

...41 self.assertFormError(response, 'form', 'slug', [u'This field is required.'])42 self.assertTemplateUsed(response, 'views/article_form.html')43 self.assertEqual(num_articles, Article.objects.count(),44 "Number of Articles should not have changed.")45 def test_create_custom_save_article(self):46 """47 Creates a new article using a custom form class with a save method48 that alters the slug entered.49 """50 view_url = '/views/create_update/create_custom/article/'51 response = self.client.post(view_url, {52 'title': 'Test Article',53 'slug': 'this-should-get-replaced',54 'author': 1,55 'date_created': datetime.datetime(2007, 6, 25),56 })57 self.assertRedirects(response,58 '/views/create_update/view/article/some-other-slug/',59 target_status_code=404)60class UpdateDeleteObjectTest(TestCase):61 fixtures = ['testdata.json']62 def test_update_object_form_display(self):63 """64 Verifies that the form was created properly and with initial values.65 """66 response = self.client.get('/views/create_update/update/article/old_article/')67 self.assertTemplateUsed(response, 'views/article_form.html')68 self.assertEquals(unicode(response.context['form']['title']),69 u'<input id="id_title" type="text" name="title" value="Old Article" maxlength="100" />')70 def test_update_object(self):71 """72 Verifies the updating of an Article.73 """74 response = self.client.post('/views/create_update/update/article/old_article/', {75 'title': 'Another Article',76 'slug': 'another-article-slug',77 'author': 1,78 'date_created': datetime.datetime(2007, 6, 25),79 })80 article = Article.objects.get(pk=1)81 self.assertEquals(article.title, "Another Article")82 def test_delete_object_confirm(self):83 """84 Verifies the confirm deletion page is displayed using a GET.85 """86 response = self.client.get('/views/create_update/delete/article/old_article/')87 self.assertTemplateUsed(response, 'views/article_confirm_delete.html')88 def test_delete_object(self):89 """90 Verifies the object actually gets deleted on a POST.91 """92 view_url = '/views/create_update/delete/article/old_article/'93 response = self.client.post(view_url)94 try:95 Article.objects.get(slug='old_article')96 except Article.DoesNotExist:97 pass98 else:99 self.fail('Object was not deleted.')100class PostSaveRedirectTests(TestCase):101 """102 Verifies that the views redirect to the correct locations depending on103 if a post_save_redirect was passed and a get_absolute_url method exists104 on the Model.105 """106 fixtures = ['testdata.json']107 article_model = Article108 create_url = '/views/create_update/create/article/'109 update_url = '/views/create_update/update/article/old_article/'110 delete_url = '/views/create_update/delete/article/old_article/'111 create_redirect = '/views/create_update/view/article/my-first-article/'112 update_redirect = '/views/create_update/view/article/another-article-slug/'113 delete_redirect = '/views/create_update/'114 def test_create_article(self):115 num_articles = self.article_model.objects.count()116 response = self.client.post(self.create_url, {117 'title': 'My First Article',118 'slug': 'my-first-article',119 'author': '1',120 'date_created': datetime.datetime(2007, 6, 25),121 })122 self.assertRedirects(response, self.create_redirect,123 target_status_code=404)124 self.assertEqual(num_articles + 1, self.article_model.objects.count(),125 "A new Article should have been created.")126 def test_update_article(self):127 num_articles = self.article_model.objects.count()128 response = self.client.post(self.update_url, {129 'title': 'Another Article',130 'slug': 'another-article-slug',131 'author': 1,132 'date_created': datetime.datetime(2007, 6, 25),133 })134 self.assertRedirects(response, self.update_redirect,135 target_status_code=404)136 self.assertEqual(num_articles, self.article_model.objects.count(),137 "A new Article should not have been created.")138 def test_delete_article(self):139 num_articles = self.article_model.objects.count()140 response = self.client.post(self.delete_url)141 self.assertRedirects(response, self.delete_redirect,142 target_status_code=404)143 self.assertEqual(num_articles - 1, self.article_model.objects.count(),144 "An Article should have been deleted.")145class NoPostSaveNoAbsoluteUrl(PostSaveRedirectTests):146 """147 Tests that when no post_save_redirect is passed and no get_absolute_url148 method exists on the Model that the view raises an ImproperlyConfigured149 error.150 """151 create_url = '/views/create_update/no_redirect/create/article/'152 update_url = '/views/create_update/no_redirect/update/article/old_article/'153 def test_create_article(self):154 self.assertRaises(ImproperlyConfigured,155 super(NoPostSaveNoAbsoluteUrl, self).test_create_article)156 def test_update_article(self):157 self.assertRaises(ImproperlyConfigured,158 super(NoPostSaveNoAbsoluteUrl, self).test_update_article)159 def test_delete_article(self):160 """161 The delete_object view requires a post_delete_redirect, so skip testing162 here.163 """164 pass165class AbsoluteUrlNoPostSave(PostSaveRedirectTests):166 """167 Tests that the views redirect to the Model's get_absolute_url when no168 post_save_redirect is passed.169 """170 # Article model with get_absolute_url method.171 article_model = UrlArticle172 create_url = '/views/create_update/no_url/create/article/'173 update_url = '/views/create_update/no_url/update/article/old_article/'174 create_redirect = '/urlarticles/my-first-article/'175 update_redirect = '/urlarticles/another-article-slug/'176 def test_delete_article(self):177 """178 The delete_object view requires a post_delete_redirect, so skip testing179 here.180 """...

Full Screen

Full Screen

views.py

Source:views.py Github

copy

Full Screen

1from django.shortcuts import render2from rest_framework import status3from .models import *4from django.views.generic import TemplateView5from rest_framework.views import APIView6from rest_framework.response import Response7from . import serializers8class IndexPage(TemplateView):9 def get(self,request,**kwargs):10 article_data = []11 all_articles = Article.objects.all().order_by('-created_at')[:9]12 for article in all_articles:13 article_data.append({14 'title' : article.title,15 'cover' : article.cover.url,16 'category' : article.category.title,17 'created_at' : article.created_at.date(),18 })19 promote_data = []20 all_promote_articles =Article.objects.filter(promote=True)21 for promote_article in all_promote_articles:22 promote_data.append({23 'category':promote_article.category.title,24 'title' : promote_article.title,25 'author': promote_article.author.user.first_name +' '+ promote_article.author.user.last_name,26 'avatar':promote_article.author.avatar.url if promote_article.author.avatar else None,27 'cover': promote_article.cover.url if promote_article.cover else None,28 'created_at' : promote_article.created_at.date(),29 })30 context = {31 'article_data' : article_data,32 'promote_article_data': promote_data,33 }34 return render(request,'index.html',context)35## contact page36class ContactPage(TemplateView):37 template_name = "page-contact.html"38class AllArticleAPIView(APIView):39 def get(self,request,format=None):40 try:41 all_articles = Article.objects.all().order_by('-created_at')[:11]42 data = []43 for article in all_articles:44 data.append({45 'title':article.title,46 'cover':article.cover.url if article.cover else None,47 'content': article.content,48 'created_at':article.created_at,49 'category':article.category.title,50 'author':article.author.user.first_name+' '+article.author.user.last_name,51 'promote':article.promote,52 })53 return Response({'data':data},status=status.HTTP_200_OK)54 except:55 return Response({'status':"internal server error, we'll check it later"},status=status.HTTP_500_INTERNAL_SERVER_ERROR)56class SingleArticleAPIView(APIView):57 def get(self,request, format=None):58 try:59 #article_title = request.query_params.get('article_title')60 article_title = request.query_params.get('article_title')61 article = Article.objects.filter(title__contains=article_title)62 print(article)63 serialized_data= serializers.SingleArticleSerializer(article,many=True)64 data=serialized_data.data65 print(article)66 return Response({'data':data}, status=status.HTTP_200_OK)67 except:68 return Response({'status':"Internal Server error"},status=status.HTTP_500_INTERNAL_SERVER_ERROR)69 #except Exception as e:70 # print(e)71class SrearchArticleAPIView(APIView):72 def get(self,request, format=None):73 try:74 from django.db.models import Q75 query=request.GET['query']76 articles=Article.objects.filter(Q(content__icontains=query))77 data=[]78 for article in articles:79 data.append({80 "title":article.title,81 "cover":article.cover.url if article.cover else None,82 "content":article.content,83 "created_at":article.created_at,84 "category":article.category.title,85 "author":article.author.user.first_name+ ' '+article.author.user.last_name,86 "promote":article.promote,87 })88 return Response({'data':data}, status=status.HTTP_200_OK)89 except:90 return Response({'status': "Internal Server error,search"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)91class SubmitArticleAPIView(APIView):92 def post(self,request,format=None):93 try:94 serializer=serializers.SubmitArticleSerializer(data=request.data)95 if serializer.is_valid():96 title=serializer.data.get('title')97 cover=request.FILES['cover']98 content=serializer.data.get('content')99 category_id=serializer.data.get('category_id')100 authory_id=serializer.data.get('author_id')101 promote=serializer.data.get('promote')102 else:103 return Response({'status':'bad request.'},status=status.HTTP_400_BAD_REQUEST)104 user = User.objects.get(id=authory_id)105 author= UserProfile.objects.get(user=user)106 category=Category.objects.get(id=category_id)107 article=Article()108 article.title=title109 article.cover=cover110 article.content=content111 article.category=category112 article.author=author113 article.promote=promote114 article.save()115 return Response({'status':'OK'},status=status.HTTP_200_OK)116 except:117 return Response({'status': "Internal Server error,submit"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)118class UpdateArticleAPIView(APIView):119 def post(self,request,format=None):120 try:121 serializer=serializers.UpdateArticleCoverSerializer(data=request.data)122 if serializer.is_valid():123 article_id=serializer.data.get('article_id')124 cover=request.FILES['cover']125 else:126 return Response({'status':'Bad reuest'}, status=status.HTTP_400_BAD_REQUEST)127 Article.objects.filter(id=article_id).update(cover=cover)128 return Response({'status':'OK'},status=status.HTTP_200_OK)129 except:130 return Response({'status': "Internal Server error,update"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)131class DeleteArticleAPIView(APIView):132 def post(self,request,format=None):133 try:134 serializer=serializers.DeleteArticleSerializer(data=request.data)135 if serializer.is_valid():136 article_id=serializer.data.get('article_id')137 else:138 return Response({'status':'bad request'},status=status.HTTP_400_BAD_REQUEST)139 Article.objects.filter(id=article_id).delete()140 return Response({'stats':'OK'},status=status.HTTP_200_OK)141 except:...

Full Screen

Full Screen

elasticSearchWrapper.py

Source:elasticSearchWrapper.py Github

copy

Full Screen

1#Andrei Simion 20182from elasticsearch import Elasticsearch3from elasticsearch_dsl import Index, Text, DocType, Date, Keyword, GeoPoint, Search, Q4from elasticsearch_dsl.connections import connections5from articleWrapper import *6from dateutil import parser7from tfidf import tfidfWrapper8import gensim9tfidf_wrapper = tfidfWrapper("C:/textePublicatiiRelevante/")10tfidf_wrapper.trainTfidf()11#tfidf_wrapper.loadTfidfModel()12class Article(DocType):13 Title = Text(analyzer='snowball')14 Publication = Text()15 Link = Text()16 Content = Text(analyzer='snowball')17 Keywords = Keyword()18 Keywords_tfidf = Keyword()19 Publishing_Date = Date()20 #GeoLocations = GeoPoint()21 Locations = Text()22 Persons = Text()23 Organizations = Text()24 class Index:25 name = 'news'26 #call save method of the superclass to add article to elasticsearch27 def save(self, ** kwargs):28 return super(Article, self).save(** kwargs)29def deleteIndex(indexName):30 index = Index(indexName)31 index.delete(ignore=404)32def createIndex(indexName):33 index = Index(indexName)34 #register a doc_type with the index35 index.document(Article)36 index.create()37def addArticleToIndexDSL(articlePath):38 article = Article()39 document = open(articlePath + ".txt", encoding = "utf8").read()40 title, publishingDate, link, publication = parseArticleInfoFile(articlePath)41 persons, locations, organizations = parseArticleEntityFile(articlePath)42 keywords = parseArticleTopicFile(articlePath, topKeywordsN=10)43 keywords_tfidf = tfidf_wrapper.getKeywordsForArticle(articlePath + ".txt")44 #print(keywords_tfidf)45 #initialize object with parsed data46 article.Title = title47 article.Publication = publication48 article.Link = link49 article.Content = document50 article.Keywords = keywords51 article.Keywords_tfidf = keywords_tfidf52 article.Publishing_Date = publishingDate53 article.Organizations = organizations54 article.Persons = persons55 #article.GeoLocations = getLocationsCoordinates(locations)56 article.locations = locations57 #label as used in doc2Vec58 articleLabel = articlePath.split('/')59 articleLabel = articleLabel[len(articleLabel) - 2] + articleLabel[len(articleLabel) - 1] 60 article.meta.id = articleLabel61 print('saving article ' + str(article.meta.id))62 article.save()63#returns article info based on articleID64#WARNING: articleID MUST match 65#WARNING: the doc label used in the doc2vec training66def searchArticle(articleID):67 s = Search()68 q = Q("multi_match", query= articleID, fields=['_id'])69 s = s.query(q)70 response = s.execute()71 #the id doesn't exist, return None72 if len(response.hits) == 0:73 return None74 hit = response.hits[0]75 title = hit.Title76 publication = hit.Publication77 publishing_date = parser.parse(hit.Publishing_Date)78 keywords = hit.Keywords79 80 return title, publication, publishing_date81 82#converts entire elasticsearch db to dict for caching83#should be quite speedy as it uses scan for bulk data extraction84#returns dict with keys as doc labels and values as tuples of the85#following form: (tile, publication, pubDate, Content)86def createESDict():87 #initialize connection to elasticsearch88 connections.create_connection(hosts=['localhost'])89 print(connections.get_connection().cluster.health())90 dict = {}91 92 #get standard search object93 s = Article.search()94 s.filter('range', _id= "")95 96 results = s.scan()97 i = 098 for res in results:99 dict[res.meta.id] = (res.Title, res.Publication,100 res.Publishing_Date, res.Content)101 i += 1102 return dict103def extractData(esDict, articleLabel):104 #write in plot relevant info, consider adding pub date as well?105 print(esDict[articleLabel][1])106 107 """wtf is this"""108 #publication = esDict[articleLabel][1].split('.')109 #publication = publication[1] + "." + publication[2] 110 publication = esDict[articleLabel][1]111 title = esDict[articleLabel][0]112 headline = publication + ": " + title[:40] + "..."113 text = esDict[articleLabel][3]114 return publication, title, headline, text115if __name__ == "__main__":116 #initialize connection117 connections.create_connection(hosts=['localhost'])118 print(connections.get_connection().cluster.health())119 120 """ WARNING: Decommenting this will cause the ENTIRE saved data 121 within elasticsearch to be deleted"""122 deleteIndex('news')123 print('deleted index..')124 createIndex("news")125 dirs = getArticleDirs("C:/textePublicatiiRelevante/")126 for dir in dirs:127 for file in os.listdir(dir):128 if file.endswith(".txt"):129 article = dir + "/" + os.path.splitext(file)[0]...

Full Screen

Full Screen

controllers.py

Source:controllers.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from flask import render_template, request, flash, url_for, redirect3from sqlalchemy import desc4from apps import app, db5from apps.models import (6 Article,7 Comment8)9@app.route('/', methods=['GET'])10def article_list():11 context = {}12 context['article_list'] = Article.query.order_by(desc(Article.date_created)).all()13 return render_template("home.html", context=context, active_tab='timeline')14@app.route('/article/create/', methods=['GET', 'POST'])15def article_create():16 if request.method == 'GET':17 return render_template('article/create.html', active_tab='article_create')18 elif request.method == 'POST':19 article_data = request.form20 article = Article(21 title = article_data['title'],22 author = article_data['author'],23 category = article_data['category'],24 content = article_data['content']25 )26 db.session.add(article)27 db.session.commit()28 flash(u'게시글이 작성되었습니다.', 'success')29 return redirect(url_for('article_list'))30@app.route('/article/update/<int:id>', methods=['GET', 'POST'])31def article_update(id):32 article = Article.query.get(id)33 if request.method == 'GET':34 return render_template('article/update.html', article=article)35 elif request.method == 'POST':36 article_data = request.form37 article = Article.query.get(id)38 article.title = article_data['title']39 article.author = article_data['author']40 article.category = article_data['category']41 article.content = article_data['content']42 db.session.commit()43 flash(u'게시글이 수정되었습니다.', 'success')44 return redirect(url_for('article_detail', id=id))45@app.route('/article/detail/<int:id>', methods=['GET'])46def article_detail(id):47 article = Article.query.get(id)48 comments = article.comments.order_by(desc(Comment.date_created)).all()49 return render_template('article/detail.html', article=article, comments=comments)50@app.route('/article/delete/<int:id>', methods=['GET', 'POST'])51def article_delete(id):52 article = Article.query.get(id)53 if request.method =='GET':54 return render_template('article/delete.html')55 56 db.session.delete(article)57 db.session.commit()58 flash(u'게시글을 삭제하였습니다.', 'success')59 return redirect(url_for('article_list'))60#61# @comment controllers62#63@app.route('/comment/create/<int:article_id>', methods=['GET', 'POST'])64def comment_create(article_id):65 if request.method =='GET':66 return render_template('comment/create.html')67 elif request.method == 'POST':68 comment_data = request.form69 comment = Comment(70 71 author = comment_data['author'],72 email = comment_data['email'],73 content = comment_data['content'],74 password = comment_data['password'],75 article = Article.query.get(article_id)76 )77 db.session.add(comment)78 db.session.commit()79 flash(u'댓글을 작성하였습니다.', 'success')80 return redirect(url_for('article_detail', id=article_id)) 81#82# @error Handlers83#84# Handle 404 errors85@app.errorhandler(404)86def page_not_found(e):87 return render_template('404.html'), 40488# Handle 500 errors89@app.errorhandler(500)90def server_error(e):...

Full Screen

Full Screen

article.controller.ts

Source:article.controller.ts Github

copy

Full Screen

1import { BackendValidation } from '@app/shared/pipes/backendValidation.pipe';2import { User } from '@app/user/decorators/user.decorator';3import { AuthGuard } from '@app/user/guards/auth.guard';4import { UserEntity } from '@app/user/user.entity';5import {6 Body,7 Controller,8 Delete,9 Get,10 Param,11 Post,12 Put,13 Query,14 UseGuards,15 UsePipes,16} from '@nestjs/common';17import { DeleteResult } from 'typeorm';18import { ArticleService } from '@app/article/article.service';19import { CreateArticleDto } from '@app/article/dto/createArticle.dto';20import { ArticleResponseInterface } from '@app/article/type/articleResponse.interface';21import { ArticlesResponseInterface } from '@app/article/type/articlesResponse.interface';22@Controller('articles')23export class ArticleController {24 constructor(private readonly articleService: ArticleService) {}25 @Get('feed')26 @UseGuards(AuthGuard)27 async getCurrentUserFeed(28 @Query() query: any,29 @User() currentUser: UserEntity,30 ): Promise<ArticlesResponseInterface> {31 const articles = await this.articleService.getCurrentUserFeed(32 query,33 currentUser,34 );35 return articles;36 }37 @Get()38 async getArticles(39 @User() user: UserEntity,40 @Query() query: any,41 ): Promise<ArticlesResponseInterface> {42 return await this.articleService.findAll(user, query);43 }44 @Get('/:slug')45 async getBySlug(46 @Param('slug') slug: string,47 ): Promise<ArticleResponseInterface> {48 const article = await this.articleService.getArticleBySlug(slug);49 return this.articleService.buildArticleResponse(article);50 }51 @Post()52 @UsePipes(new BackendValidation())53 @UseGuards(AuthGuard)54 async createArticle(55 @User() user: UserEntity,56 @Body('article') createdArticleDto: CreateArticleDto,57 ): Promise<ArticleResponseInterface> {58 const article = await this.articleService.createArticle(59 user,60 createdArticleDto,61 );62 return this.articleService.buildArticleResponse(article);63 }64 @Post('/:slug/favorite')65 @UseGuards(AuthGuard)66 async addArticleToFavorites(67 @Param('slug') slug: string,68 @User('id') currentUserId: number,69 ): Promise<ArticleResponseInterface> {70 const article = await this.articleService.addArticleToFavorites(71 slug,72 currentUserId,73 );74 return this.articleService.buildArticleResponse(article);75 }76 @Delete('/:slug/favorite')77 @UseGuards(AuthGuard)78 async deleteArticleToFavorites(79 @Param('slug') slug: string,80 @User('id') currentUserId: number,81 ): Promise<ArticleResponseInterface> {82 const article = await this.articleService.deleteArticleToFavorites(83 slug,84 currentUserId,85 );86 return this.articleService.buildArticleResponse(article);87 }88 @Delete('/:slug')89 @UseGuards(AuthGuard)90 async deleteArticle(91 @Param('slug') slug: string,92 @User() user: UserEntity,93 ): Promise<DeleteResult> {94 return await this.articleService.deleteArticle(slug, user);95 }96 @Put('/:slug')97 @UseGuards(AuthGuard)98 @UsePipes(new BackendValidation())99 async updateArticle(100 @Param('slug') slug: string,101 @Body('article') article: CreateArticleDto,102 @User() user: UserEntity,103 ): Promise<ArticleResponseInterface> {104 const updatedArticle = await this.articleService.updateArticle(105 slug,106 article,107 user,108 );109 return this.articleService.buildArticleResponse(updatedArticle);110 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import { linkTo } from '@storybook/addon-links';5import { withInfo } from '@storybook/addon-info';6import { withKnobs, text, boolean, number } from '@storybook/addon-knobs/react';7import { Article } from 'storybook-root';8const stories = storiesOf('Article', module);9stories.addDecorator(withKnobs);10stories.add('Article', () => (11 title={text('Title', 'Title')}12 author={text('Author', 'Author')}13 date={text('Date', 'Date')}14 image={text('Image', 'Image')}15 text={text('Text', 'Text')}16 link={text('Link', 'Link')}17));18import React from 'react';19import { View, Text, Image } from 'react-native';20const Article = ({ title, author, date, image, text, link }) => (21 <Text>{title}</Text>22 <Text>{author}</Text>23 <Text>{date}</Text>24 <Image source={{ uri: image }} />25 <Text>{text}</Text>26 <Text>{link}</Text>27);28export default Article;29import React from 'react';30import { storiesOf } from '@storybook/react-native';31import { action } from '@storybook/addon-actions';32import { linkTo } from '@storybook/addon-links';33import { withInfo } from '@storybook/addon-info';34import { withKnobs, text, boolean, number } from '@storybook/addon-knobs/react';35import Article from './article';36const stories = storiesOf('Article', module);37stories.addDecorator(withKnobs);38stories.add('Article', () => (

Full Screen

Using AI Code Generation

copy

Full Screen

1import { article } from 'storybook-root';2import { article } from 'storybook-root';3import { article } from 'storybook-root';4import { article } from 'storybook-root';5import { article } from 'storybook-root';6import { article } from 'storybook-root';7import { article } from 'storybook-root';8import { article } from 'storybook-root';9import { article } from 'storybook-root';10import { article } from 'storybook-root';11MIT © [Saurabh Kumar](

Full Screen

Using AI Code Generation

copy

Full Screen

1var article = require('storybook-root').article;2var article = require('storybook-root').article;3var article = require('storybook-root').article;4var article = require('storybook-root').article;5var article = require('storybook-root').article;6var article = require('storybook-root').article;7var article = require('storybook-root').article;8var article = require('storybook-root').article;9var article = require('storybook-root').article;10var article = require('storybook-root').article;11var article = require('storybook-root').article;12var article = require('storybook-root').article;13var article = require('storybook-root').article;14var article = require('storybook-root').article;15var article = require('storybook-root').article;16var article = require('storybook-root').article;17var article = require('storybook-root').article;18var article = require('storybook-root').article;19var article = require('storybook-root').article;

Full Screen

Using AI Code Generation

copy

Full Screen

1import { article } from 'storybook-root';2import { storiesOf } from '@storybook/react';3import React from 'react';4import { Article } from './Article';5storiesOf('Article', module).add('default', () => (6 <Article article={article} />7));8MIT © [Arielle Fennema](

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful