def test_get_articles_order_by_id_desc(self): insert_amount = 30 with self.app.test_request_context(), self.db.atomic(): prefix = 'testarticle' articles = [ dict(id=prefix + str(i), title=prefix, text_type=prefix, source_text=prefix) for i in range(insert_amount) ] Article.insert_many(articles).execute() resp = self.client.get(self.api_url_base + '/articles/', query_string={ 'limit': insert_amount, 'order': 'id', 'desc': 'true' }) self.assertResponseRestful(resp) expected_ids = sorted([article['id'] for article in articles], reverse=True) result_ids = [ article['id'] for article in self.get_json(resp)['articles'] ] self.assertListEqual(expected_ids, result_ids)
def test_get_articles_without_private_article(self): insert_amount = 30 with self.app.test_request_context(), self.db.atomic(): prefix = 'testarticle' articles = [ dict(id=prefix + str(i), title=prefix, text_type=prefix, source_text=prefix) for i in range(insert_amount) ] Article.insert_many(articles).execute() prefix = 'testarticle-p' articles = [ dict(id=prefix + str(i), title=prefix, text_type=prefix, source_text=prefix, public=False) for i in range(insert_amount) ] Article.insert_many(articles).execute() resp = self.client.get(self.api_url_base + '/articles/', query_string={'limit': insert_amount * 2}) self.assertResponseRestful(resp) articles = self.get_json(resp)['articles'] self.assertEqual(len(articles), insert_amount)
def test_get_cates_order_by_article_count(self): insert_amount = 10 prefix = 'testcate' with self.app.test_request_context(), self.db.atomic(): cates = [dict(id=prefix + str(i), name=prefix + str(i)) for i in range(insert_amount)] Category.insert_many(cates).execute() for index, cate in enumerate(cates): articles = [dict(id=str(index) + str(i), title='hello', text_type='md', source_text='# hello', category=cate['id']) for i in range((index + 1) * 2)] Article.insert_many(articles).execute() resp = self.client.get(self.api_url_base + '/categories/', query_string={'order': 'article_count', 'desc': 'true'}) self.assertResponseRestfulAndSuccess(resp) categories = self.get_json(resp)['categories'] result_counts = [cate['article_count'] for cate in categories] expected_counts = sorted(result_counts, reverse=True) self.assertListEqual(result_counts, expected_counts)
def test_get_articles_filter_by_nonexist_category(self): from random import choice insert_amount_per_cate = 30 category_amount = 3 cate_prefix = 'cate' article_prefix = 'art' with self.app.test_request_context(), self.db.atomic(): cates = [ dict(id=cate_prefix + str(i), name=cate_prefix + str(i)) for i in range(category_amount) ] Category.insert_many(cates).execute() cate_to_insert = choice(cates)['id'] articles = [ dict(id=article_prefix + str(i), title=article_prefix, text_type=article_prefix, source_text=article_prefix, category=cate_to_insert) for i in range(insert_amount_per_cate) ] Article.insert_many(articles).execute() resp = self.client.get(self.api_url_base + '/articles/', query_string={ 'limit': insert_amount_per_cate, 'category': cate_to_insert + '_' }) self.assertResponseRestful(resp) articles = self.get_json(resp)['articles'] self.assertEqual(len(articles), 0)
def test_user_not_authenticated(self): Article(title='title', body='body').put() url = reverse('article_admin_delete', kwargs={'id': 1}) resp = self.client.get(url) self.assertEqual(resp.status_code, 302) self.assertEqual(Article.all().count(), 1)
def test_article_exist(self): key = Article(title='title', body='body').put() self.users_login('admin@localhost', is_admin=True) url = reverse('article_admin_delete', kwargs={'id': key.id()}) resp = self.client.get(url) self.assertRedirects(resp, reverse('index')) self.assertEqual(Article.all().count(), 0)
def test_article_does_not_exist(self): Article(key_name='randomkey', title='title', body='body').put() self.users_login('admin@localhost', is_admin=True) url = reverse('article_admin_delete', kwargs={'id': 1}) resp = self.client.get(url) self.assertEqual(resp.status_code, 404) self.assertEqual(Article.all().count(), 1)
def test_user_not_admin(self): Article(title='title', body='body').put() self.users_login('user@localhost', is_admin=False) url = reverse('article_admin_delete', kwargs={'id': 1}) resp = self.client.get(url) self.assertEqual(resp.status_code, 302) self.assertEqual(Article.all().count(), 1)
def arts(request): system = SystemObject(request) data = dict() fw = [] #items = DentoData.objects.using('dento').all().order_by('-added') #gallery = Gallery.objects.get(id=2) site = SitePortal.objects.get(id=1) # lekarze items = Category.objects.optfilter({ 'site': site.id }) for cat in items: if cat.dentoid is not None: arts = DentoData.objects.using('dento').filter(linkID=cat.dentoid).order_by('-added') for item in arts: text = '' art = Article() art.save() system.language.set_non_existent_language_items(art, ArticleLanguage) art.get_language(system.language.currentLanguage.id) if item.intro is not None: item.intro = item.intro.replace('\n',u'</p><p>') item.intro = change_image(item.ID, item.intro, art) text = text + '<p>' + item.intro + '</p>' if item.body is not None: item.body = item.body.replace('\n',u'</p><p>') item.body = change_image(item.ID, item.body, art) text = text + '<p>' + item.body + '</p>' if item.title is not None: item.title = item.title.replace('\n\n',u'') item.title = change_image(item.ID, item.title, art, only_main=True, show=True) art.language.title = item.title fw.append(art.dentomainimage) art.language.text = text art.visits = item.displayCount if item.added: art.date = item.added art.category = cat art.save() art.language.save() art.sites.add(site.site) if item.active: art.active.add(site.site) time.sleep(0.2) data.update({ 'data': fw }) t = loader.get_template('imp/impart.html') c = RequestContext(request, data) return HttpResponse(t.render(c))
def test_delete_non_empty_cate(self): with self.app.test_request_context(): cate = Category.create(id='testcate', name='testcate') Article.create(id='testart', title='testart', text_type='md', source_text='# hello', category=cate) resp = self.client.delete(self.api_url_base + '/category/' + cate.id) self.assertResponseRestful(resp) self.assertResponseErrorInField(resp, 'not_empty')
def add(request): if request.method == "GET": # ... return render(request, "add.html") elif request.method == "POST": form = request.POST article = Article(title=form["title"], text=form["text"], author=request.user) article.save() return redirect(homepage)
def test_patch_orm_v1(self, objects): """ 0.00038 sec [sqlite in memory] """ articles = Mock() objects.filter.return_value = articles Article.update_all_articles_with_blank_title_v1('new_val') objects.filter.assert_called_with(title='') articles.update.assert_called_with(title='new_val')
def test_patch_orm_v2(self, objects): """ 0.00050 sec [sqlite in memory] """ first_article = Mock() second_article = Mock() objects.filter.return_value = [first_article, second_article] Article.update_all_articles_with_blank_title_v2('new_val') objects.filter.assert_called_with(title='') first_article.title = 'new_val' first_article.save.assert_called_with() second_article.title = 'new_val' second_article.save.assert_called_with()
def test_model_mommy_v1_v2_v3(self): """ v1 0.00429 sec [sqlite in memory] v2 0.00490 sec [sqlite in memory] v3 0.00557 sec [sqlite in memory] """ mommy.make(Article, title='title', _quantity=2) three, four = mommy.make(Article, title='', _quantity=2) Article.update_all_articles_with_blank_title_v1('new_val') new_val_articles = Article.objects.filter(title='new_val') new_val_ids = set(new_val_articles.values_list('id', flat=True)) self.assertSetEqual(new_val_ids, {three.id, four.id})
def get_articles(self, categoryitem, lang, site): cats = self.get_items_as_tree(categoryitem, 0) manager = BaseManager() manager.fetchOptions = { 'site': site.id, 'active': 1, 'activesite': site.id } manager.model = Article() manager.modelLanguage = ArticleLanguage() manager.order = 'date' manager.debugger.filename = 'megamenu.py' manager.rangeItemsStart = 1 manager.rangeItemsEnd = 5 manager.moduleName = '__adm_Articles__' items = [] if 1: #for cat in cats: #manager.fetchOptions.update({ 'category__id': cat.id }) manager.fetchOptions.update({'category': cats}) manager.fetch_items(default_filter=False) if manager.items: for item in manager.items: item.get_language(lang.id) items.append(item) manager.items = items return manager.items[:5]
def test_post_invalid_missing_title(self): self.users_login('admin@localhost', is_admin=True) data = {'body': 'article_body'} self.client.post(self.url, data) self.assertEqual(Article.all().count(), 0)
class IndexView(BlogMixin, ListView): """ The index page of the site. Contains the body and the titles of all the articles. """ template_name = 'index.html' queryset = Article.all().order('-created_at')
def handle(self, *args, **options): Article.objects.all().delete() Chapter.objects.all().delete() for file in glob.glob("programme/chapitre*/index.md"): title = open(file).read().split('\n')[0][1:].strip() Chapter( number=file.split('chapitre-')[1].split('/')[0], slug=slugify(title), title=title, content='\n'.join(open(file).read().split('\n')[1:]), ).save() for file in glob.glob("programme/chapitre*/*.md"): if 'index.md' in file: continue chapter_number = file.split('chapitre-')[1].split('/')[0] chapter = Chapter.objects.get(number=chapter_number) title = open(file).read().split('\n')[0][1:].strip() Article( number=int(file.split('/')[-1].replace('.md', '')), slug=slugify(title), title=title, content='\n'.join(open(file).read().split('\n')[1:]), chapter=chapter, ).save()
def test_reading_entry_str(self): username = '******' link = 'https://www.superlink.com/article.html' article = Article(link=link) user = User(username=username) entry = ReadingEntry(user=user, article=article) self.assertEqual("{} - {}".format(username, link[:50]), str(entry))
def choices(self, system): s = ((datetime.date.today() + datetime.timedelta(days=1)) - datetime.timedelta(6 * 365 / 12)) manager = BaseManager() manager.model = Article() manager.modelLanguage = ArticleLanguage() manager.order = '-date' manager.fetchOptions = { 'date_gte': s.isoformat(), 'site': system.portal.activeSite.id, 'active': system.requester.rData['selectedactivity'], 'activesite': system.requester.rData['activesite'] } manager.rangeItemsStart = None manager.rangeItemsEnd = None manager.fetch_items() items = manager.items #items = Article.objects.optfilter(manager.fetchOptions) #print '--->',items choices = [] if items is not None: manager.set_language(system.language.currentLanguage) for il in items: choices.append((il.id, il.language)) self.fields['article'].choices = choices
def test_post_valid(self): self.users_login('admin@localhost', is_admin=True) data = {'title': 'article_title', 'body': 'article_body'} resp = self.client.post(self.url, data) self.assertRedirects(resp, reverse('index')) self.assertEqual(Article.all().count(), 1)
def test_post_valid(self): self.users_login('admin@localhost', is_admin=True) data = {'body': 'new_body', 'title': 'new_title'} self.client.post(self.url, data) article = Article.get(self.key) self.assertEqual(article.title, 'new_title') self.assertEqual(article.body, 'new_body')
def get_queryset(self): slug, period = sites_info[0]['slug'], ALL try: slug = self.kwargs['slug'] period = self.kwargs['period'] except KeyError: pass site_name = Site.objects.get(slug=slug) return Article.query_articles(site_name, period)
def test_model_mommy(self): """ 0.00435 sec [sqlite in memory] """ mommy.make(Article, title='title', _quantity=2) three = mommy.make(Article, title='') articles = Article.get_set_of_articles_blank_title() self.assertSetEqual(articles, {three})
def test_patch_orm(self, objects): """ 0.00029 sec [sqlite in memory] """ result = Mock() objects.filter.return_value = [result] articles = Article.get_set_of_articles_blank_title() self.assertSetEqual(articles, {result}) objects.filter.assert_called_with(title='')
def post_an_article(self, public=True, author=None): with self.app.test_request_context(): cate = self.insert_a_category() if public else None return Article.create(id='testarticle', title='testarticle', text_type='md', source_text='# hello world', is_commentable='false', public=public, category=cate, author=author)
def test_get_an_article_src_without_permission(self): with self.app.test_request_context(): article = Article.create(id='testart', title='testart', text_type='md', source_text='# hello', is_commentable=False) resp = self.client.get(self.api_url_base + '/article/' + article.id, query_string={'with_src': 'true'}) self.assertResponseErrorInField(resp, 'permission')
def get_comments(aid): '''``GET`` |API_URL_BASE|/article/:aid/comments/ Get information of all comments to an article. :param limit: **Query** limit amount of comment per page, default: |COMMENT_LIST_DEFAULT_LIMIT| :param page: **Query** page control, start from zero, default: 1 Response JSON: .. code-block:: javascript // success { $errors: null, comments: [ { id: integer, nickname: string, content: string, time: datetime, reply_to: integer // maybe null if no references. } ] } // failed {$errors: {article_id: 'this article doesn't not exist.'}} Permission required: ``READ_COMMENT`` ''' default_limit = app_config['COMMENT_LIST_DEFAULT_LIMIT'] try: author_id = (Article.select(Article.author) .where(Article.id == aid).get()).author_id except Article.DoesNotExist: return {'article_id': '无法找到这篇文章,可能已经被删除'} page = request.args.get('page', 1, type=int) - 1 limit = request.args.get('limit', default_limit, type=int) query = (Comment.select() .where(Comment.article == aid) .offset(page * limit).limit(limit + 1)) if current_user.get_id() != author_id: query = query.where(Comment.reviewed == True) # noqa: E712 comments = [comment.to_dict() for comment in query] is_more = len(comments) > limit return None, {'is_more': is_more, 'comments': comments[:limit]}
def test_fetch(self, mock_requests): article = Article(link='http://test') mock_requests.get.return_value.status_code = 200 mock_requests.get.return_value.content = '<html>\ <head><title>Test</title></head>\ <body><h1>Test</h1>\ <p>content</p>\ </html>' retrieve_article_content(article) mock_requests.get.assert_called_with(article.link) self.assertEqual(article.status, cst.READY_STATUS)
def setUp(self): self.reset_database() self.enable_comment_review(True) self.logout() self.login_as_author() with self.app.test_request_context(): self.art = Article.create(id='testart', title='', text_type='', source_text='', author='author') self.path_prefix = self.api_url_base + '/article/' + self.art.id
def test_write_a_comment_reply_to_mismatch_article_comment(self): with self.app.test_request_context(), self.db.atomic(): article = Article.create(id='testart_', title='', text_type='', source_text='') payload = {'nickname': 'author_test', 'content': 'test comment'} resp = self.client.patch(self.api_url_base + '/article/' + article.id + '/comment/' + '10010', content_type='application/json', data=json_dumps(payload)) self.assertResponseErrorInField(resp, 'comment_id')
def home(request): if request.user: most_rated_products = Rate.get_most_rated_products(max_size=4) most_hot_products = Product.get_hot(max_size=4) recent_portfolios = Portfolio.get_latest(max_size=4) recent_articles = Article.get_recommended() activities = Activity.get_banner_activity() types = ProductType.objects.all() return render(request, "welcome.html", {"most_rated_products": most_rated_products, "recent_articles": recent_articles, "types": types, 'activities': activities, "recent_portfolios": recent_portfolios, "most_hot_products": most_hot_products}) else: return render(request, "home.html")
class TestUpdateArticle(AppEngineTestCase): def setUp(self): create_blog() self.key = Article(title='title123', body='body123').put() self.url = reverse('article_admin_update', kwargs={'id': self.key.id()}) def test_user_not_admin(self): self.users_login('user@localhost', is_admin=False) resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) def test_user_not_authenticated(self): resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) def test_form_contains_article_title_and_body(self): self.users_login('admin@localhost', is_admin=True) resp = self.client.get(self.url) self.assertContains(resp, 'title123') self.assertContains(resp, 'body123') def test_post_no_body(self): self.users_login('admin@localhost', is_admin=True) data = {'title': 'new_title'} self.client.post(self.url, data) article = Article.get(self.key) self.assertEqual(article.title, 'title123') self.assertEqual(article.body, 'body123') def test_post_no_title(self): self.users_login('admin@localhost', is_admin=True) data = {'body': 'new_body'} self.client.post(self.url, data) article = Article.get(self.key) self.assertEqual(article.title, 'title123') self.assertEqual(article.body, 'body123') def test_post_valid(self): self.users_login('admin@localhost', is_admin=True) data = {'body': 'new_body', 'title': 'new_title'} self.client.post(self.url, data) article = Article.get(self.key) self.assertEqual(article.title, 'new_title') self.assertEqual(article.body, 'new_body')
def test_get_a_comment_mismatch_article(self): with self.app.test_request_context(), self.db.atomic(): article = Article.create(id='testart_', title='', text_type='', source_text='') comment = Comment.create(content='comment_test', article=self.art, nickname='tester', reviewed=True) resp = self.client.get(self.api_url_base + '/article/' + article.id + '/comment/' + str(comment.id)) self.assertResponseErrorInField(resp, 'comment_id')
def load_to_db_from_csv(file): sites_names = (REDDIT, ML_MASTERY, ML_WEEKLY, MIT_NEWS) sites = [Site.objects.get(name=site) for site in sites_names] sites_dict = dict(zip(sites_names, sites)) with open(file, 'r') as f: reader = csv.reader(f) articles = [ Article(title=row[0], link=row[1], timestamp=row[2], site=sites_dict[row[3]]) for row in reader ] Article.objects.bulk_create(articles)
def test_get_a_private_article_without_permission(self): self.login_as_author() with self.app.test_request_context(): article = Article.create(id='testart', title='testart', text_type='md', source_text='# hello', is_commentable=False, public=False) self.logout() self.login_as_su() resp = self.client.get(self.api_url_base + '/article/' + article.id) self.assertResponseErrorInField(resp, 'permission')
def __init__(self, request, *args, **kwargs): super(SystemObject, self).__init__(request, *args, **kwargs) self.manager = Manager() self.manager.fetchOptions = { 'site': self.portal.reqsite, 'active': 1, 'activesite': self.portal.reqsite } self.urls.show_items = 'core.view.articleadmin.show_items' self.manager.model = Article() self.manager.modelLanguage = ArticleLanguage() self.manager.order = '-date' self.manager.debugger.filename = 'articleadmin.py' self.manager.moduleName = '__adm_Articles__' self.category = Manager() self.category.model = Category() self.category.order = 'parent' self.category.fetchOptions = { 'site': self.portal.reqsite, 'active': 1, 'activesite': self.portal.reqsite } self.category.modelLanguage = CategoryLanguage()
def test_vanilla_django(self): """ 0.02883 sec [sqlite in memory] """ blog = Blog.objects.create(title='Blog title') user = User.objects.create_user(username='******', password='******') article_kwargs = { 'blog': blog, 'creator': user, 'body': 'body', } Article.objects.create(title='title_one', **article_kwargs) Article.objects.create(title='title_two', **article_kwargs) three = Article.objects.create(**article_kwargs) articles = Article.get_set_of_articles_blank_title() self.assertSetEqual(articles, {three})
def test_get_by_id_or_404_article_found(self): key = Article(title='title', body='body').put() result = Article.get_by_id_or_404(key.id()) self.assertEqual(key, result.key())
def get_object(self): obj_id = self.kwargs.get('id', None) return Article.get_by_id_or_404(obj_id)
def test_get_by_id_or_404_id_is_none(self): with self.assertRaises(Http404): Article.get_by_id_or_404(None)
def test_get_by_id_or_404_no_article(self): key = Article(title='title', body='body').put() free_key = key.id() + 1 with self.assertRaises(Http404): Article.get_by_id_or_404(free_key)
def get_pop_articles(): articles = cache.get("pop_articles_news") if not articles: articles = Article.get_recommended(type=1) # cache.set("pop_articles", articles) return articles