def setUp(self): self.testbed = testbed.Testbed() # Then activate the testbed, which prepares the service stubs for use. self.testbed.activate() # Next, declare which service stubs you want to use. self.testbed.init_datastore_v3_stub() # enable memcache self.testbed.init_memcache_stub() self.testbed.init_user_stub(enable=True) self.testbed.init_search_stub(enable=True) self.testbed.init_urlfetch_stub() self.testbed.init_app_identity_stub() self.testbed.init_blobstore_stub() self.testbed.setup_env( USER_EMAIL='*****@*****.**', USER_ID='123', USER_IS_ADMIN='1', overwrite=True) # Clear ndb's in-context cache between tests. # This prevents data from leaking between tests. # Alternatively, you could disable caching by # using ndb.get_context().set_cache_policy(False) ndb.get_context().clear_cache() self.tags = Tags() self.categories = Categories() self.posts = Posts() self.form = PostForm()
def setUp(self): self.testbed = testbed.Testbed() # Then activate the testbed, which prepares the service stubs for use. self.testbed.activate() # Next, declare which service stubs you want to use. self.testbed.init_datastore_v3_stub() # enable memcache self.testbed.init_memcache_stub() self.testbed.init_user_stub(enable=True) self.testbed.init_search_stub(enable=True) self.testbed.setup_env( USER_EMAIL='*****@*****.**', USER_ID='123', USER_IS_ADMIN='1', overwrite=True) # Clear ndb's in-context cache between tests. # This prevents data from leaking between tests. # Alternatively, you could disable caching by # using ndb.get_context().set_cache_policy(False) ndb.get_context().clear_cache() self.tags = Tags() self.categories = Categories() self.posts = Posts() self.form = PostForm() self.uploadform = UploadForm()
def setUp(self): self.testbed = testbed.Testbed() # Then activate the testbed, which prepares the service stubs for use. self.testbed.activate() # Next, enable csrf for proper rendering of forms self.app.config['WTF_CSRF_ENABLED'] = True self.testbed.init_user_stub() self.testbed.init_blobstore_stub() self.testbed.init_datastore_v3_stub() self.testbed.init_app_identity_stub() self.testbed.init_urlfetch_stub() # enable memcache self.testbed.init_memcache_stub() self.categories = Categories() self.tags = Tags()
def clean(self): cleaned_data = super(CategoryAddForm, self).clean() name = cleaned_data.get("name") q = Categories.all().filter("name =", name) result = q.get() if result is not None: #menu name already exist raise forms.ValidationError("Category name already exist") return cleaned_data
def form_valid(self, form): q = Posts( author=self.request.user, title=form.cleaned_data['title'], slug=str(slugify(form.cleaned_data['title'])), body=form.cleaned_data['body'], is_active=form.cleaned_data['is_active'], created=datetime.datetime.now().date()) q.put() tags = self.request.POST.get('tags', False) if tags: splitted_tags = tags.split(",") for split in splitted_tags: result = Tags.all().filter("tag =", split).get() if result is None: result = Tags(tag=split).put() PostsTags(tag=result, post=q).put() categories = form.cleaned_data['cat'] if categories: for split in categories: if "-" in split: #this is a parent value parent_children_array = split.split("-") result = Categories.get_by_id(int(parent_children_array[1]), parent=Categories.get_by_id(int(parent_children_array[0]))) else: result = Categories.get_by_id(int(split)) if result is not None: PostsCategories(category=result, post=q).put() #add images short_image = self.request.FILES.get('short_image', False) large_image = self.request.FILES.get('large_image', False) if short_image: q.small_image = Images(content=db.Blob(short_image.read())).put() q.put() if large_image: q.large_image = Images(content=db.Blob(large_image.read())).put() q.put() return super(Admin_Blog_Posts_AddController, self).form_valid(form)
def get(self, request, slug, *arg, **kwargs): context = self.get_context_data(**kwargs) """ return the post list """ cat = Categories.all().filter("name =", slug).get() catposts = PostsCategories.all().filter("category =", cat).fetch(None) results = [] for posts in catposts: results.append(posts.post) context['posts'] = results return self.render_to_response(context)
def create_blog_view(request): context = {} user = request.user user_id = Account.objects.filter(username=request.user).first() if not user.is_authenticated: return redirect('must_authenticate') form = CreateBlogPostForm(request.POST or None, request.FILES or None) #print(request.POST.get('title')) if form.is_valid(): obj = form.save(commit=False) author = Account.objects.filter(email=user.email).first() obj.author = author obj.save() category_list_unsplit = form.cleaned_data['category'] if category_list_unsplit: category_list = category_list_unsplit.split(':') for category in category_list: cat_obj = Categories() cat_obj.blog_id = BlogPost.objects.get( title=form.cleaned_data['title']) cat_obj.category = category cat_obj.save() form = CreateBlogPostForm() for f in request.FILES.getlist('other_image'): img = Extra_Image() img.blog_id = obj img.image = f img.save() context['form'] = form return render(request, 'blog/create_blog.html', context)
class TestViews(BlogTestBase): maxDiff = None def setUp(self): self.testbed = testbed.Testbed() # Then activate the testbed, which prepares the service stubs for use. self.testbed.activate() # Next, declare which service stubs you want to use. self.testbed.init_datastore_v3_stub() # enable memcache self.testbed.init_memcache_stub() self.testbed.init_user_stub(enable=True) self.testbed.init_search_stub(enable=True) self.testbed.setup_env( USER_EMAIL='*****@*****.**', USER_ID='123', USER_IS_ADMIN='1', overwrite=True) # Clear ndb's in-context cache between tests. # This prevents data from leaking between tests. # Alternatively, you could disable caching by # using ndb.get_context().set_cache_policy(False) ndb.get_context().clear_cache() self.tags = Tags() self.categories = Categories() self.posts = Posts() self.form = PostForm() self.uploadform = UploadForm() def test_tags_view(self): passed_days, remaining_days = calculate_work_date_stats() response = self.client.get((url_for('view_all_tags'))) site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template('tags.html', user_status=users.is_current_user_admin(),siteupdated=site_updated,\ daysleft=remaining_days,dayspassed=passed_days,tags=self.tags.to_json(), codeversion=CODEVERSION) self.assertEqualHTML(rendered_template, response.data.decode('utf-8')) def test_categories_view(self): passed_days, remaining_days = calculate_work_date_stats() response = self.client.get((url_for('view_all_categories'))) site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template('categories.html', user_status=users.is_current_user_admin(),siteupdated=site_updated,\ daysleft=remaining_days,dayspassed=passed_days,tags=self.tags.to_json(), codeversion=CODEVERSION) self.assertEqualHTML(rendered_template, response.data.decode('utf-8')) def test_archives_url_resolves_to_archive_page(self): passed_days, remaining_days = calculate_work_date_stats() flash(MSG) response = self.client.get((url_for('archives'))) post_tag_names = self.tags.to_json() site_updated = self.posts.site_last_updated() posts_json = self.posts.to_json() rendered_template = render_template('archives.html', user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=posts_json, codeversion=CODEVERSION, form=self.form, uploadform=self.uploadform, posts_tags_names=post_tag_names) self.assertEqualHTML(rendered_template, response.data.decode('utf-8')) def test_archives_url_content_is_ok(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary") passed_days, remaining_days = calculate_work_date_stats() flash(MSG) response = self.client.get((url_for('archives'))) post_tag_names = self.tags.to_json() site_updated = self.posts.site_last_updated() posts_json = self.posts.to_json() rendered_template = render_template('archives.html', user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=posts_json, codeversion=CODEVERSION, form=self.form, uploadform=self.uploadform, posts_tags_names=post_tag_names) self.assertEqualHTML(rendered_template, response.data.decode('utf-8')) def test_index_page_returns_correct_html(self): passed_days, remaining_days = calculate_work_date_stats() response = self.client.get('/') # create a request object site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template("posts.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=self.posts.to_json(), codeversion=CODEVERSION, form=self.form, uploadform=self.uploadform) self.assertEqualHTML(rendered_template, response.data.decode('utf-8')) def test_index_page_with_content_is_ok(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary") passed_days, remaining_days = calculate_work_date_stats() response = self.client.get((url_for('index'))) # create a request object site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template("posts.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=self.posts.to_json(), codeversion=CODEVERSION, form=self.form, uploadform=self.uploadform) self.assertEqualHTML(rendered_template.decode('utf-8'), response.data.decode('utf-8')) def test_selected_post_page_returns_correct_html(self): passed_days, remaining_days = calculate_work_date_stats() category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary") current_post = self.posts.get_by_title("a title") post_tag_names = current_post.get_tag_names() other_posts_tags = self.posts.get_other_tags(current_post.key.id()) related_posts = [] response = self.client.get(url_for('view_a_post', category="category", year=current_post.timestamp.year, month=current_post.timestamp.month, title="a title")) for post in self.posts: if post.key != current_post.key: for tag in post.tags: if tag in other_posts_tags: related_posts.append(post) category = post.category.get().category site_updated = self.posts.site_last_updated() flash(MSG) answers_form = AnswerRadioForm() answers_form.r_answers.choices = [("t", answer.p_answer) for answer in current_post.answers] rendered_template = render_template('singlepost.html', user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, RelatedPosts=related_posts, \ Post=current_post.to_json(), posttagnames=post_tag_names, category=category, answers_field = answers_form) self.assertEqual(rendered_template.encode("utf-8"), response.data) def test_select_post_with_related_posts_returns_correct_html(self): passed_days, remaining_days = calculate_work_date_stats() category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary") test_tags_related = ["a new tag", "a different tag"] new_rel_tag_keys = self.tags.add(test_tags_related) self.posts.add("a better title", "body without text", category_key, new_rel_tag_keys, "this is new a summary") current_post = self.posts.get_by_title("a title") post_tag_names = current_post.get_tag_names() other_posts_tags = self.posts.get_other_tags(current_post.key.id()) response = self.client.get(url_for('view_a_post', category="category", year=current_post.timestamp.year, month=current_post.timestamp.month, title="a title")) related_posts = self.posts.get_related_posts(current_post.id) category = current_post.category.get().category site_updated = self.posts.site_last_updated() flash(MSG) answers_form = AnswerRadioForm() answers_form.r_answers.choices = [("t", answer.p_answer) for answer in current_post.answers] rendered_template = render_template('singlepost.html', user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, RelatedPosts=related_posts, \ Post=current_post.to_json(), posttagnames=post_tag_names, category=category, answers_field=answers_form) self.assertEqual(rendered_template.encode("utf-8"), response.data) def test_tag_pag_returns_correct_html(self): passed_days, remaining_days = calculate_work_date_stats() response = self.client.get((url_for('index'))) # create a request object site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template("posts.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=self.posts.to_json(), codeversion=CODEVERSION, form=self.form, uploadform=self.uploadform) self.assertEqualHTML(rendered_template, response.data.decode('utf-8')) def test_delete_post(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post_key = self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary") response = self.client.delete(url_for('delete_post', id=post_key.id())) self.assertEqual("OK", response.json["msg"]) def test_get_post(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) post_key = self.posts.add("a title", "body text", category_key, existing_tag_keys, "this is a summary") asked_post = post_key.get() post_tag_names = asked_post.get_tag_names() tag_names = self.tags.get_names() data = {u"title": asked_post.title, u"body": asked_post.body, u"category": asked_post.category.get().category, u"category": category_key.get().category, u"id": str(asked_post.key.id()).decode('utf8'), \ u"tags": post_tag_names, u"summary":asked_post.summary, u"timestamp": asked_post.timestamp.strftime(DATEFORMAT).decode('utf8') , u"updated": asked_post.updated.strftime(DATEFORMAT).decode('utf8'), u"answers":[] } response = self.client.get(url_for("get_post", id=post_key.id())) self.assertDictEqual(data, response.json) def test_add_post(self): existing_tags = [u"a new new tag", u"a new tag"] freezer = freeze_time(u"2017-03-20") freezer.start() json_data = {u'category': u'category', u'tags': existing_tags, u"summary": u"this is a summary", u'title': u'a title',u'body': u'body text', u'timestamp': datetimeformat(datetime.now()).decode("utf-8"), u'updated': datetimeformat(datetime.now()).decode("utf-8"), "answers" : [{u'p_answer':'a potential answer', u'is_correct':True, u'statistics': 0.0, u'nof_times_selected': 0}]} response = self.client.post(url_for('main'), content_type='application/json', data=json.dumps(json_data)) json_data[u"id"] = u'4' self.assertDictEqual(json_data, response.json) freezer.stop() def test_api_posts(self): existing_tags = [u"a new new tag", u"a new tag"] freezer = freeze_time(u"2017-03-20 17:48:18") freezer.start() json_data = {u'category': u'category', u'tags': existing_tags, u"summary": u"this is a summary", u'title': u'a title', u'body': u'body text', u'timestamp': datetimeformat(datetime.now()) .decode("utf-8"), u'updated': datetimeformat(datetime.now()).decode("utf-8"), "answers": [{u'p_answer': 'a potential answer', u'is_correct': True, u'statistics': 0.0, u'nof_times_selected': 0}]} response = self.client.post(url_for('main'), content_type='application/json', data=json.dumps(json_data)) json_data[u"id"] = u'4' self.assertDictEqual(json_data, response.json) freezer.stop() def test_api_posts_with_files(self): existing_tags = [u"a new new tag", u"a new tag"] freezer = freeze_time(u"2017-03-20 17:48:18") freezer.start() json_data = {u'category': u'category', u'tags': existing_tags, u"summary": u"this is a summary", u'title': u'a title', u'body': u'body text', u'timestamp': datetimeformat(datetime.now()) .decode("utf-8"), u'updated': datetimeformat(datetime.now()).decode("utf-8"), "answers": [{u'p_answer': 'a potential answer', u'is_correct': True, u'statistics': 0.0, u'nof_times_selected': 0}]} response = self.client.post(url_for('main'), content_type='application/json', data=json.dumps(json_data)) json_data[u"id"] = u'4' self.assertDictEqual(json_data, response.json) freezer.stop() def test_no_post(self): response = self.client.get(url_for('main')) self.assertFalse(response.json) def test_edit_post(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] editing_tags = ["a new tag", "tag to added"] # final tags are "a new tag", "tag to added" existing_tag_keys = self.tags.add(existing_tags) post_key = self.posts.add("a title", "body text", category_key, existing_tag_keys, "this is a summary") self.posts.add("a title 2", "body text 2", category_key, existing_tag_keys, "this is a summary 2") updating_post = post_key.get() json_data = {'category': 'a new category', 'tags': editing_tags, 'title': 'a new title', 'body': 'body text', 'summary': 'this is a new summary', 'answers':[]} response = self.client.put(url_for('edit_post', id=post_key.id()), content_type='application/json', data=json.dumps(json_data)) tag_names = [u"a new tag", u"a new new tag", u"tag to added"] post_tag_names = [u"a new tag", u"tag to added"] data = {u"title": 'a new title', u"body": updating_post.body, u"category": "a new category", u"id": str(updating_post.key.id()).decode('utf8'), \ u"tags": post_tag_names, 'summary': 'this is a new summary', u"timestamp": updating_post.timestamp.strftime(DATEFORMAT).decode('utf8') , u"updated": updating_post.updated.strftime(DATEFORMAT).decode('utf8'), u"answers":updating_post.answers } self.assertDictEqual(data, response.json) def test_edit_a_post_view(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) post_key = self.posts.add("a title", "body text", category_key, existing_tag_keys, "this is a summary") response = self.client.get(url_for('edit_a_post_view', postkey=post_key)) flash(MSG) site_updated = self.posts.site_last_updated() passed_days, remaining_days = calculate_work_date_stats() rendered_template = render_template('posts.html', user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, codeversion=CODEVERSION, form=self.form, uploadform=self.uploadform) self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_about_page(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys, "this is a summary") requested_post = self.posts.get_by_title('about') response = self.client.get(url_for('aboutpage')) passed_days, remaining_days = calculate_work_date_stats() site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template('about.html',user_status=users.is_current_user_admin(), siteupdated=site_updated,\ daysleft=remaining_days,dayspassed=passed_days,Post=requested_post, codeversion=CODEVERSION) self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_searchresults(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys, "this is a summary") passed_days, remaining_days = calculate_work_date_stats() site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template("posts.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, posts=self.posts.to_json(), codeversion=CODEVERSION, form=self.form, uploadform=self.uploadform) response = self.client.get(url_for('searchresults', q="body")) self.assertEqualHTML( response.data.decode('utf8'),rendered_template.decode('utf8')) def test_search_query(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys, "this is a summary") query_string = "body" results = query_search_index(query_string) posts_ids = find_posts_from_index(results) self.posts.filter_matched(posts_ids) response = self.client.get(url_for('searchsite', query="body")) return self.assertDictEqual({u'data':self.posts.to_json()}, response.json) def test_view_filtered_posts_by_tag(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys) second_tags = ["a new second tag", "a new new second tag"] second_tag_keys = self.tags.add(second_tags) self.posts.add("about second post", "body secod text", category_key, second_tag_keys) self.posts.filter_by_tag('a new tag') flash(MSG) passed_days, remaining_days = calculate_work_date_stats() site_updated = self.posts.site_last_updated() rendered_template = render_template("posts.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=self.posts.to_json(), codeversion=CODEVERSION, form=self.form, uploadform=self.uploadform) response = self.client.get(path='/tags/a new tag') return self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_view_filtered_posts_by_category(self): category_key = self.categories.add("a category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys) second_tags = ["a new second tag", "a new new second tag"] second_tag_keys = self.tags.add(second_tags) self.posts.add("about second post", "body secod text", category_key, second_tag_keys) self.posts.filter_by_category('a category') passed_days, remaining_days = calculate_work_date_stats() site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template("posts.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=self.posts.to_json(), codeversion=CODEVERSION, form=self.form, uploadform=self.uploadform) response = self.client.get(path='/categories/a category') return self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_404_not_found_page(self): response = self.client.get(path='/a path not existing') flash(MSG) rendered_template = render_template('404.html') return self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_user(self): response = self.client.get(path='/user') return self.assertDictEqual({'user_status':users.is_current_user_admin()},response.json) def test_redirect_on_search(self): response = self.client.get((url_for('index', q="test redirect on search"))) # cre return self.assertStatus(response, 302) def test_feed(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys) response = self.client.get(path='/recent.atom') feed = AtomFeed('Recent Articles', feed_url='http://localhost/recent.atom', url=request.url_root) feed = self.posts.add_to_feed(feed, request.url) return self.assertEqual(feed.to_string(), response.data.decode('utf8')) def test_rebuild_index(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys) response = self.client.get(path='/rebuild_index') return self.assertStatus(response, 302) def test_api_answers_post_method(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary", [{"p_answer":"ans1", "is_correct":True},{"p_answer":"ans2","is_correct":False}]) json_data_f = {"p_answer":"ans2","is_correct":"True"} response = self.client.post(url_for('answers', title="a title"), content_type='application/json', data=json.dumps(json_data_f))#, headers={"csrf_token":csrf_token}) self.assertDictEqual({u'msg': u'Sorry, no attempts left!', u'result': False, u'remaining_attempts': 0,u'alert_type':u'warning', u'answers_stats':{}}, response.json) json_data_f = {"p_answer": "ans2", "is_correct": "True"} response = self.client.post(url_for('answers', title="a title"), content_type='application/json', data=json.dumps(json_data_f)) self.assertDictEqual({u'msg': u'Sorry, no attempts left!',u'alert_type':u'warning', u'result': False, u'remaining_attempts':-1, u'answers_stats': {} }, response.json) def test_api_answers_post_method_correct_guess(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary", [{"p_answer": "ans1", "is_correct": True}, {"p_answer": "ans2", "is_correct": False}]) json_data_f = {"p_answer": "ans1", "is_correct": "True"} response = self.client.post(url_for('answers', title="a title"), content_type='application/json', data=json.dumps(json_data_f)) # , headers={"csrf_token":csrf_token}) self.assertDictEqual({u'msg': u'Great!', u'result': True, u'remaining_attempts': 0, u'alert_type': u'success', u'answers_stats': {u'Answer': u'Selection', u'ans1': 1, u'ans2': 0}}, response.json) def test_is_cookie_set(self): with app.test_client() as c: c.post(url_for('ga_accept'), follow_redirects=True) c_value = request.cookies.get('ga_accepted') self.assertEqual(c_value, 'True') def test_is_cookie_set_false(self): with app.test_client() as c: c.post(url_for('ga_decline'), follow_redirects=True) c_value = request.cookies.get('ga_accepted') self.assertEqual(c_value, 'False') def test_accept_google_analytics(self): with app.test_client() as c: c.post(url_for('ga_accept'), follow_redirects=True) accept_google_analytics() self.assertTrue(app.jinja_env.globals['ga_accepted']) with app.test_client() as c: c.post(url_for('ga_decline'), follow_redirects=True) accept_google_analytics() self.assertFalse(app.jinja_env.globals['ga_accepted']) def test_questions_view(self): category_key = self.categories.add("reconstructing a test") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary", [{"p_answer": "ans1", "is_correct": True}, {"p_answer": "ans2", "is_correct": False}]) category_key = self.categories.add("reconstructing a test") test_tags = ["a tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title here", "body to test the question text", category_key, new_tag_keys, "this is a summary", [{"p_answer": "a test answ correct", "is_correct": True}, {"p_answer": "a wrong tet answer", "is_correct": False}]) response = self.client.get(path="/questions/reconstructing a test") self.posts.filter_by_category("reconstructing a test") flash(MSG) passed_days, remaining_days = calculate_work_date_stats() site_updated = self.posts.site_last_updated() self.posts.to_answers_form() rendered_template = render_template("questions.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=self.posts, codeversion=CODEVERSION) return self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_redirect_nonwww(self): app.config['SERVER_NAME'] = "arsakian.com" with app.test_request_context(): with app.test_client() as c: response = c.get(url_for('index', _external=True)) self.assertEqual(response.location, "http://www.arsakian.com/") response = c.get(url_for('archives', _external=True)) self.assertEqual(response.location, "http://www.arsakian.com/archives") app.config['SERVER_NAME'] = None # def test_upload(self): # output = StringIO() # output.write('hello there') # # response = self.client.post(url_for('upload'), buffered=True, # content_type='multipart/form-data', # data={'file_field': (output, 'hello there')}) # # # self.assertEqual('ok',response.data)
class TestViews(BlogTestBase): maxDiff = None def setUp(self): self.testbed = testbed.Testbed() # Then activate the testbed, which prepares the service stubs for use. self.testbed.activate() # Next, declare which service stubs you want to use. self.testbed.init_datastore_v3_stub() # enable memcache self.testbed.init_memcache_stub() self.testbed.init_user_stub(enable=True) self.testbed.init_search_stub(enable=True) self.testbed.init_urlfetch_stub() self.testbed.init_app_identity_stub() self.testbed.init_blobstore_stub() self.testbed.setup_env( USER_EMAIL='*****@*****.**', USER_ID='123', USER_IS_ADMIN='1', overwrite=True) # Clear ndb's in-context cache between tests. # This prevents data from leaking between tests. # Alternatively, you could disable caching by # using ndb.get_context().set_cache_policy(False) ndb.get_context().clear_cache() self.tags = Tags() self.categories = Categories() self.posts = Posts() self.form = PostForm() def test_tags_view(self): passed_days, remaining_days = calculate_work_date_stats() response = self.client.get((url_for('view_all_tags'))) site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template('tags.html', user_status=users.is_current_user_admin(),siteupdated=site_updated,\ daysleft=remaining_days,dayspassed=passed_days,tags=self.tags.to_json(), codeversion=CODEVERSION) self.assertEqualHTML(rendered_template, response.data.decode('utf-8')) def test_categories_view(self): passed_days, remaining_days = calculate_work_date_stats() response = self.client.get((url_for('view_all_categories'))) site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template('categories.html', user_status=users.is_current_user_admin(),siteupdated=site_updated,\ daysleft=remaining_days,dayspassed=passed_days,tags=self.tags.to_json(), codeversion=CODEVERSION) self.assertEqualHTML(rendered_template, response.data.decode('utf-8')) def test_archives_url_resolves_to_archive_page(self): passed_days, remaining_days = calculate_work_date_stats() flash(MSG) response = self.client.get((url_for('archives'))) post_tag_names = self.tags.to_json() site_updated = self.posts.site_last_updated() posts_json = self.posts.to_json() rendered_template = render_template('archives.html', user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=posts_json, codeversion=CODEVERSION, form=self.form, posts_tags_names=post_tag_names) self.assertEqualHTML(rendered_template, response.data.decode('utf-8')) def test_archives_url_content_is_ok(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary") passed_days, remaining_days = calculate_work_date_stats() flash(MSG) response = self.client.get((url_for('archives'))) post_tag_names = self.tags.to_json() site_updated = self.posts.site_last_updated() posts_json = self.posts.to_json() rendered_template = render_template('archives.html', user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=posts_json, codeversion=CODEVERSION, form=self.form, posts_tags_names=post_tag_names) self.assertEqualHTML(rendered_template, response.data.decode('utf-8')) def test_index_page_returns_correct_html(self): passed_days, remaining_days = calculate_work_date_stats() response = self.client.get('/') # create a request object site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template("posts.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=self.posts.to_json(), codeversion=CODEVERSION, form=self.form) self.assertEqualHTML(rendered_template, response.data.decode('utf-8')) def test_index_page_with_content_is_ok(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary") passed_days, remaining_days = calculate_work_date_stats() response = self.client.get((url_for('index'))) # create a request object site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template("posts.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=self.posts.to_json(), codeversion=CODEVERSION, form=self.form) self.assertEqualHTML(rendered_template.decode('utf-8'), response.data.decode('utf-8')) def test_selected_post_page_returns_correct_html(self): passed_days, remaining_days = calculate_work_date_stats() category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary") current_post = self.posts.get_by_title("a title") post_tag_names = current_post.get_tag_names() other_posts_tags = self.posts.get_other_tags(current_post.key.id()) related_posts = [] with open(os.path.join(TEST_IMAGE)) as f: self.assertTrue(current_post.add_blob(f.read(), TEST_IMAGE, 'image/jpeg')) response = self.client.get(url_for('view_a_post', category="category", year=current_post.timestamp.year, month=current_post.timestamp.month, title="a title")) for post in self.posts: if post.key != current_post.key: for tag in post.tags: if tag in other_posts_tags: related_posts.append(post) category = post.category.get().category site_updated = self.posts.site_last_updated() flash(MSG) answers_form = AnswerRadioForm() answers_form.r_answers.choices = [("t", answer.p_answer) for answer in current_post.answers] rendered_template = render_template('singlepost.html', user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, RelatedPosts=related_posts, \ Post=current_post.to_json(), posttagnames=post_tag_names, category=category, answers_field=answers_form) self.assertEqual(rendered_template.encode("utf-8"), response.data) def test_select_post_with_related_posts_returns_correct_html(self): passed_days, remaining_days = calculate_work_date_stats() category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary") test_tags_related = ["a new tag", "a different tag"] new_rel_tag_keys = self.tags.add(test_tags_related) self.posts.add("a better title", "body without text", category_key, new_rel_tag_keys, "this is new a summary") current_post = self.posts.get_by_title("a title") post_tag_names = current_post.get_tag_names() other_posts_tags = self.posts.get_other_tags(current_post.key.id()) response = self.client.get(url_for('view_a_post', category="category", year=current_post.timestamp.year, month=current_post.timestamp.month, title="a title")) related_posts = self.posts.get_related_posts(current_post.id) category = current_post.category.get().category site_updated = self.posts.site_last_updated() flash(MSG) answers_form = AnswerRadioForm() answers_form.r_answers.choices = [("t", answer.p_answer) for answer in current_post.answers] rendered_template = render_template('singlepost.html', user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, RelatedPosts=related_posts, \ Post=current_post.to_json(), posttagnames=post_tag_names, category=category, answers_field=answers_form) self.assertEqual(rendered_template.encode("utf-8"), response.data) def test_tag_pag_returns_correct_html(self): passed_days, remaining_days = calculate_work_date_stats() response = self.client.get((url_for('index'))) # create a request object site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template("posts.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=self.posts.to_json(), codeversion=CODEVERSION, form=self.form) self.assertEqualHTML(rendered_template, response.data.decode('utf-8')) def test_delete_post(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post_key = self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary") response = self.client.delete(url_for('delete_post', id=post_key.id())) self.assertEqual("OK", response.json["msg"]) self.assertItemsEqual([], self.posts) def test_delete_post_with_image(self): with open(os.path.join(TEST_IMAGE)) as f: img_stringIO = StringIO.StringIO(f.read()) # in memory read post, _, _ = self.create_post() post.add_blob(img_stringIO.read(), TEST_IMAGE, 'image/jpeg') response = self.client.delete(url_for('delete_post', id=post.key.id())) self.assertEqual("OK", response.json["msg"]) self.assertEqual(0, len(self.posts)) def test_get_post(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) post_key = self.posts.add("a title", "body text", category_key, existing_tag_keys, "this is a summary") asked_post = post_key.get() post_tag_names = asked_post.get_tag_names() tag_names = self.tags.get_names() data = {u"title": asked_post.title, u"body": asked_post.body, u"category": asked_post.category.get().category, u"category": category_key.get().category, u"id": str(asked_post.key.id()).decode('utf8'), \ u"tags": [{u"key": str(existing_tag_keys[0]).decode('utf8'), u"val":existing_tag_keys[0].get().tag}, {u"key": str(existing_tag_keys[1]).decode('utf8'), u"val":existing_tag_keys[1].get().tag}], u"summary":asked_post.summary, u"timestamp": asked_post.timestamp.strftime(DATEFORMAT).decode('utf8') , u"updated": asked_post.updated.strftime(DATEFORMAT).decode('utf8'), u"answers":[], u'images': [] } response = self.client.get(url_for("get_post", id=post_key.id())) self.assertDictEqual(data, response.json) def test_add_post(self): existing_tags = [u"a new new tag", u"a new tag"] freezer = _freeze_time(u"2017-03-20") freezer.start() json_data = {u'category': u'category', u'tags': existing_tags, u"summary": u"this is a summary", u'title': u'a title',u'body': u'body text', u'timestamp': datetimeformat(datetime.now()).decode("utf-8"), u'updated': datetimeformat(datetime.now()).decode("utf-8"), u"answers" : [{u'p_answer':u'a potential answer', u'is_correct':True, u'statistics': 0.0, u'nof_times_selected': 0}]} response = self.client.post(url_for('main'), content_type='application/json', data=json.dumps(json_data)) json_data[u"id"] = u'4' json_data[u'images'] = [] json_data[u'tags'] = [{u"key": str(tag_key).decode("utf-8"), u"val": tag_key.get().tag} for tag_key in self.posts[0].tags] self.assertDictEqual(json_data, response.json) freezer.stop() def test_api_posts(self): existing_tags = [u"a new new tag", u"a new tag"] freezer = _freeze_time(u"2017-03-20 17:48:18") freezer.start() json_data = {u'category': u'category', u'tags': existing_tags, u"summary": u"this is a summary", u'title': u'a title', u'body': u'body text', u'timestamp': datetimeformat(datetime.now()) .decode("utf-8"), u'updated': datetimeformat(datetime.now()).decode("utf-8"), u"answers": [{u'p_answer': u'a potential answer', u'is_correct': True, u'statistics': 0.0, u'nof_times_selected': 0}]} response = self.client.post(url_for('main'), content_type='application/json', data=json.dumps(json_data)) json_data[u"id"] = u'4' json_data[u'images'] = [] json_data[u'tags'] = [{u"key": str(tag_key).decode("utf-8"), u"val": tag_key.get().tag} for tag_key in self.posts[0].tags] self.assertDictEqual(json_data, response.json) freezer.stop() def test_api_posts_with_image(self): post, _, _ = self.create_post() import io with open(os.path.join(TEST_IMAGE), 'rb') as f: data = dict( image=[(io.BytesIO(f.read()), TEST_IMAGE)], ) response = self.client.post(path='/api/posts/{}/images'.format(post.id), data=data, content_type='multipart/form-data', follow_redirects=True) self.assertDictEqual({'image_key': u'encoded_gs_file:YXBwX2RlZmF1bHRfYnVja2V0LzIwMTlfMV80XzE2ei5naWY='}, response.json) with open(os.path.join(TEST_IMAGE), 'rb') as f: data = dict( wrong_key=[(io.BytesIO(f.read()), TEST_IMAGE)], ) response = self.client.post(path='/api/posts/{}/images'.format(post.id), data=data, content_type='multipart/form-data', follow_redirects=True) return self.assertStatus(response, 500) def test_api_posts_with_files(self): existing_tags = [u"a new new tag", u"a new tag"] with freeze_time(u"2019-11-05"): with open(TEST_IMAGE, 'rb') as f: byte_content = f.read() with open(TEST_IMAGE2, 'rb') as f: byte_content_2 = f.read() images = [{'filename': "C:\\fakepath\\{}".format(TEST_IMAGE), 'url': "data:image/jpeg;base64,{}".format(b64encode(byte_content))}, {'filename': "C:\\fakepath\\{}".format(TEST_IMAGE2), 'url': "data:image/jpeg;base64,{}".format(b64encode(byte_content_2))}] json_data = {u'category': u'category', u'tags': existing_tags, u"summary": u"this is a summary", u'title': u'a title', u'body': u'body text', u'timestamp': datetimeformat(datetime.now()) .decode("utf-8"), u'updated': datetimeformat(datetime.now()).decode("utf-8"), u"answers":[], u'images':images} response = self.client.post(url_for('main'), content_type='application/json', data=json.dumps(json_data)) tags = [{ u"key": str(tag_key).decode("utf-8"), u"val": tag_key.get().tag} for tag_key in self.posts[0].tags] json_data = {u"id":"4",u'category': u'category', u'tags': tags, u"summary": u"this is a summary", u'title': u'a title', u'body': u'body text', u'timestamp': datetimeformat(datetime.now()) .decode("utf-8"), u'updated': datetimeformat(datetime.now()).decode("utf-8"), u"answers": [], u'images': [{u'blob_key': u'encoded_gs_file:YXBwX2RlZmF1bHRfYnVja2V0LzIwMTlfMV80XzE2ei5naWY=', u'filename': TEST_IMAGE}, {u'blob_key': u'encoded_gs_file:YXBwX2RlZmF1bHRfYnVja2V0LzEyXzNfNF8zXzEyei5wbmc=', u'filename': TEST_IMAGE2}]} self.assertDictEqual(json_data, response.json) def test_no_post(self): response = self.client.get(url_for('main')) self.assertFalse(response.json) def test_edit_post_add_answers(self): post, _, tag_keys = self.create_post() editing_tags = ["a new tag", "tag to added"] json_data = {u'category': u'a new category', 'tags': editing_tags, 'title': 'a new title', 'body': 'body text', u'summary': u'this is a new summary', 'answers': [{u"p_answer": u"ans1", "is_correct": True}, {u"p_answer": u"ans2", "is_correct": False}]} response = self.client.put(url_for('edit_post', id=post.key.id()), content_type='application/json', data=json.dumps(json_data)) tags = [{"key": str(tag_key), "val": tag_key.get().tag} for tag_key in post.tags] data = {u"title": u'a new title', u"body": post.body, u"category": u"a new category", u"id": str(post.key.id()).decode('utf8'), \ u"tags": tags, u'summary': u'this is a new summary', u"timestamp": post.timestamp.strftime(DATEFORMAT).decode('utf8') , u"updated": post.updated.strftime(DATEFORMAT).decode('utf8'), u"answers": [{u"p_answer": u"ans1", u"is_correct": True, u'statistics': 0.0, u'nof_times_selected': 0}, {u"p_answer": u"ans2", u"is_correct": False, u'statistics': 0.0, u'nof_times_selected': 0}], u'images': []} self.assertDictEqual(data, response.json) def test_edit_post(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] editing_tags = ["a new tag", "tag to added"] # final tags are "a new tag", "tag to added" existing_tag_keys = self.tags.add(existing_tags) post_key = self.posts.add("a title", "body text", category_key, existing_tag_keys, "this is a summary") self.posts.add("a title 2", "body text 2", category_key, existing_tag_keys, "this is a summary 2") updating_post = post_key.get() json_data = {u'category': u'a new category', 'tags': editing_tags, 'title': 'a new title', 'body': 'body text', u'summary': u'this is a new summary', 'answers':[]} response = self.client.put(url_for('edit_post', id=post_key.id()), content_type='application/json', data=json.dumps(json_data)) tags = [{"key": str(tag_key), "val": tag_key.get().tag} for tag_key in post_key.get().tags] data = {u"title": u'a new title', u"body": updating_post.body, u"category": u"a new category", u"id": str(updating_post.key.id()).decode('utf8'), \ u"tags": tags, u'summary': u'this is a new summary', u"timestamp": updating_post.timestamp.strftime(DATEFORMAT).decode('utf8') , u"updated": updating_post.updated.strftime(DATEFORMAT).decode('utf8'), u"answers":updating_post.answers,u'images':[], } self.assertDictEqual(data, response.json) def test_edit_a_post_view(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) post_key = self.posts.add("a title", "body text", category_key, existing_tag_keys, "this is a summary") response = self.client.get(url_for('edit_a_post_view', postkey=post_key)) flash(MSG) site_updated = self.posts.site_last_updated() passed_days, remaining_days = calculate_work_date_stats() rendered_template = render_template('posts.html', user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, codeversion=CODEVERSION, form=self.form) self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_about_page(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys, "this is a summary") requested_post = self.posts.get_by_title('about') response = self.client.get(url_for('aboutpage')) passed_days, remaining_days = calculate_work_date_stats() site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template('about.html',user_status=users.is_current_user_admin(), siteupdated=site_updated,\ daysleft=remaining_days,dayspassed=passed_days,Post=requested_post, codeversion=CODEVERSION) self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_searchresults(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys, "this is a summary") passed_days, remaining_days = calculate_work_date_stats() site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template("posts.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, posts=self.posts.to_json(), codeversion=CODEVERSION, form=self.form) response = self.client.get(url_for('searchresults', q="body")) self.assertEqualHTML( response.data.decode('utf8'),rendered_template.decode('utf8')) def test_search_query(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys, "this is a summary") query_string = "body" results = query_search_index(query_string) posts_ids = find_posts_from_index(results) self.posts.filter_matched(posts_ids) response = self.client.get(url_for('searchsite', query="body")) return self.assertDictEqual({u'data':self.posts.to_json()}, response.json) def test_view_filtered_posts_by_tag(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys) second_tags = ["a new second tag", "a new new second tag"] second_tag_keys = self.tags.add(second_tags) self.posts.add("about second post", "body secod text", category_key, second_tag_keys) self.posts.filter_by_tag('a new tag') flash(MSG) passed_days, remaining_days = calculate_work_date_stats() site_updated = self.posts.site_last_updated() rendered_template = render_template("posts.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=self.posts.to_json(), codeversion=CODEVERSION, form=self.form) response = self.client.get(path='/tags/a new tag') return self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_view_filtered_posts_by_category(self): category_key = self.categories.add("a category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys) second_tags = ["a new second tag", "a new new second tag"] second_tag_keys = self.tags.add(second_tags) self.posts.add("about second post", "body secod text", category_key, second_tag_keys) self.posts.filter_by_category('a category') passed_days, remaining_days = calculate_work_date_stats() site_updated = self.posts.site_last_updated() flash(MSG) rendered_template = render_template("posts.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=self.posts.to_json(), codeversion=CODEVERSION, form=self.form) response = self.client.get(path='/categories/a category') return self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_404_not_found_page(self): response = self.client.get(path='/a path not existing') flash(MSG) rendered_template = render_template('404.html') return self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_500_error_page(self): json_data = {u'category': u'a new category', 'tags': '', 'title': 'a new title', 'body': 'body text', u'summary': u'this is a new summary', 'answers': []} response = self.client.put(url_for('edit_post', id='34'), content_type='application/json', data=json.dumps(json_data)) accept_google_analytics() rendered_template = render_template('500.html') return self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_user(self): response = self.client.get(path='/user') return self.assertDictEqual({'user_status':users.is_current_user_admin()},response.json) def test_redirect_on_search(self): response = self.client.get((url_for('index', q="test redirect on search"))) # cre return self.assertStatus(response, 302) def test_feed(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys) response = self.client.get(path='/recent.atom') feed = AtomFeed('Recent Articles', feed_url='http://localhost/recent.atom', url=request.url_root) feed = self.posts.add_to_feed(feed, request.url) return self.assertEqual(feed.to_string(), response.data.decode('utf8')) def test_rebuild_index(self): category_key = self.categories.add("category") existing_tags = ["a new tag", "a new new tag"] existing_tag_keys = self.tags.add(existing_tags) self.posts.add("about", "body text", category_key, existing_tag_keys) response = self.client.get(path='/rebuild_index') return self.assertStatus(response, 302) def test_api_answers_post_method(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary", [{"p_answer":"ans1", "is_correct":True},{"p_answer":"ans2","is_correct":False}]) json_data_f = {"p_answer":"ans2","is_correct":"True"} response = self.client.post(url_for('answers', title="a title"), content_type='application/json', data=json.dumps(json_data_f))#, headers={"csrf_token":csrf_token}) self.assertDictEqual({u'msg': u'Sorry, no attempts left!', u'result': False, u'remaining_attempts': 0,u'alert_type':u'warning', u'answers_stats':{}}, response.json) json_data_f = {"p_answer": "ans2", "is_correct": "True"} response = self.client.post(url_for('answers', title="a title"), content_type='application/json', data=json.dumps(json_data_f)) self.assertDictEqual({u'msg': u'Sorry, no attempts left!',u'alert_type':u'warning', u'result': False, u'remaining_attempts':-1, u'answers_stats': {} }, response.json) def test_api_answers_post_method_correct_guess(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary", [{"p_answer": "ans1", "is_correct": True}, {"p_answer": "ans2", "is_correct": False}]) json_data_f = {"p_answer": "ans1", "is_correct": "True"} response = self.client.post(url_for('answers', title="a title"), content_type='application/json', data=json.dumps(json_data_f)) # , headers={"csrf_token":csrf_token}) self.assertDictEqual({u'msg': u'Great!', u'result': True, u'remaining_attempts': 0, u'alert_type': u'success', u'answers_stats': {u'Answer': u'Selection', u'ans1': 1, u'ans2': 0}}, response.json) def test_is_cookie_set(self): with app.test_client() as c: c.post(url_for('ga_accept'), follow_redirects=True) c_value = request.cookies.get('ga_accepted') self.assertEqual(c_value, 'True') def test_is_cookie_set_false(self): with app.test_client() as c: c.post(url_for('ga_decline'), follow_redirects=True) c_value = request.cookies.get('ga_accepted') self.assertEqual(c_value, 'False') def test_accept_google_analytics(self): with app.test_client() as c: c.post(url_for('ga_accept'), follow_redirects=True) accept_google_analytics() self.assertTrue(app.jinja_env.globals['ga_accepted']) with app.test_client() as c: c.post(url_for('ga_decline'), follow_redirects=True) accept_google_analytics() self.assertFalse(app.jinja_env.globals['ga_accepted']) def test_questions_view(self): category_key = self.categories.add("reconstructing a test") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary", [{"p_answer": "ans1", "is_correct": True}, {"p_answer": "ans2", "is_correct": False}]) category_key = self.categories.add("reconstructing a test") test_tags = ["a tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title here", "body to test the question text", category_key, new_tag_keys, "this is a summary", [{"p_answer": "a test answ correct", "is_correct": True}, {"p_answer": "a wrong tet answer", "is_correct": False}]) response = self.client.get(path="/questions/reconstructing a test") self.posts.filter_by_category("reconstructing a test") flash(MSG) passed_days, remaining_days = calculate_work_date_stats() site_updated = self.posts.site_last_updated() self.posts.to_answers_form() rendered_template = render_template("questions.html", user_status=users.is_current_user_admin(), siteupdated=site_updated, \ daysleft=remaining_days, dayspassed=passed_days, tags=self.tags, categories=self.categories, posts=self.posts, codeversion=CODEVERSION) self.assertEqualHTML(rendered_template.decode('utf8'), response.data.decode('utf8')) def test_redirect_nonwww(self): app.config['SERVER_NAME'] = "arsakian.com" with app.test_request_context(): with app.test_client() as c: response = c.get(url_for('index', _external=True)) self.assertEqual(response.location, "http://www.arsakian.com/") response = c.get(url_for('archives', _external=True)) self.assertEqual(response.location, "http://www.arsakian.com/archives") app.config['SERVER_NAME'] = None def test_send_image_file(self): with open(os.path.join(TEST_IMAGE)) as f: img_stringIO = StringIO.StringIO(f.read()) # in memory read post, _, _ = self.create_post() image_key = post.add_blob(img_stringIO.read(), TEST_IMAGE, 'image/jpeg') response = self.client.get(path='/images/{}'.format(TEST_IMAGE), content_type='multipart/form-data', follow_redirects=True) with open(os.path.join(TEST_IMAGE)) as f: self.assertEqual(f.read(), response.data) # with app.test_client() as c: # accept_google_analytics() # # self.assertRaises(cloudstorage.NotFoundError, c.get(path='/images/{}'.format("non existent"), # content_type='multipart/form-data', # follow_redirects=True)) def test_delete_image_from_a_post(self): with open(os.path.join(TEST_IMAGE)) as f: img_stringIO = StringIO.StringIO(f.read()) # in memory read post, _, _ = self.create_post() image_key = post.add_blob(img_stringIO.read(), TEST_IMAGE, 'image/jpeg') response = self.client.delete(url_for('delete_post_images', id=post.id, filename=TEST_IMAGE)) self.assertEqual("file deleted", response.json["msg"])
class TestModels(BlogTestBase): def setUp(self): self.testbed = testbed.Testbed() # Then activate the testbed, which prepares the service stubs for use. self.testbed.activate() # Next, declare which service stubs you want to use. self.testbed.init_datastore_v3_stub() # enable memcache self.testbed.init_memcache_stub() self.testbed.init_user_stub() self.testbed.init_blobstore_stub() self.testbed.init_app_identity_stub() self.testbed.init_urlfetch_stub() self.testbed.init_search_stub(enable=True) # Clear ndb's in-context cache between tests. # This prevents data from leaking between tests. # Alternatively, you could disable caching by # using ndb.get_context().set_cache_policy(False) ndb.get_context().clear_cache() self.tags = Tags() self.categories = Categories() self.posts = Posts() def create_answers(self, answers): answers_keys = [ Answer(p_answer=ans, is_correct=is_correct) for ans, is_correct in answers.items() ] return answers_keys def create_post_with_answers(self, answers, category="a category"): test_tags = ["a new tag", "a new new tag"] tag_keys = self.tags.add(test_tags) answers_keys = self.create_answers(answers) category_key = self.categories.add(category) summary = "a summmary" title = "a title" body = "here is a body" post_key = BlogPost(title=title, body=body, category=category_key, tags=tag_keys, summary=summary, answers=answers_keys).put() return post_key.get(), category_key, tag_keys, answers_keys def test_add_a_tag(self): tag_keys = self.tags.add(["a new tag"]) self.assertEqual("a new tag", tag_keys[0].get().tag) def test_add_a_tag_once(self): self.tags.add(["a new tag"]) tags_keys = self.tags.add(["a new tag", "a really new tag"]) self.assertEqual(len(self.tags), 2) self.assertEqual(self.tags.get_keys(["a new tag", "a really new tag"]), tags_keys) def test_add_tags(self): tag_keys = self.tags.add(["a new tag", "a second new tag"]) self.assertItemsEqual(["a new tag", "a second new tag"], [tag_keys[0].get().tag, tag_keys[1].get().tag]) def test_delete_a_tag(self): self.tags.add(["a new tag"]) self.tags.delete("a new tag") self.assertItemsEqual([], self.tags) def test_delete_tags(self): self.tags.add(["a new tag", "a second new tag"]) self.tags.delete(["a new tag", "a second new tag"]) self.assertItemsEqual([], self.tags) def test_get_keys_of_tags(self): test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.assertItemsEqual(new_tag_keys, self.tags.get_keys(test_tags)) def test_add_a_category(self): category_key = self.categories.add("category") self.assertEqual("category", category_key.get().category) def test_add_a_category_once(self): category_key = self.categories.add("category") self.assertEqual("category", category_key.get().category) self.categories.add("category") self.assertEqual(len(self.categories), 1) def test_delete_a_category(self): category_key = self.categories.add("category") self.categories.delete(category_key) self.assertItemsEqual([], self.categories) def test_get_key_of_a_category(self): self.assertEqual(self.categories.add("category"), self.categories.get_key("category")) def test_add_a_post(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post_key = self.posts.add("a title", "body text", category_key, new_tag_keys, "this is a summary") self.assertEqual("a title", post_key.get().title) self.assertEqual("body text", post_key.get().body) self.assertEqual("this is a summary", post_key.get().summary) self.assertEqual(category_key, post_key.get().category) self.assertItemsEqual(new_tag_keys, post_key.get().tags) def test_get_tags_from_posts(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys) self.assertItemsEqual(test_tags, self.posts.get_tags()) def test_get_empty_tags_from_posts(self): category_key = self.categories.add("category") test_tags = [] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys) self.assertItemsEqual(test_tags, self.posts.get_tags()) def test_get_tags_from_a_post(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys) for post in self.posts: self.assertItemsEqual(test_tags, post.get_tag_names()) def test_get_other_tags_from_a_post(self): category_key = self.categories.add("category") test_tags1 = ["a new tag", "a new new tag"] test_tags2 = ["a new tag 1", "a new new tag"] new_tag_keys1 = self.tags.add(test_tags1) new_tag_keys2 = self.tags.add(test_tags2) post_key1 = self.posts.add("a title", "body text", category_key, new_tag_keys1) self.posts.add("a title 2", "body text 2", category_key, new_tag_keys2) self.assertItemsEqual(test_tags2, self.posts.get_other_tags(post_key1.id())) def test_find_modified_tags(self): test_existing_tags = ["a new tag", "a new new tag"] editing_tags1 = ["a new tag 1", "a new new tag 2"] editing_tags2 = ["a new tag 1", "a new tag"] modified_tags = find_modified_tags(editing_tags1, test_existing_tags) self.assertItemsEqual(modified_tags, editing_tags1) modified_tags = find_modified_tags(editing_tags2, test_existing_tags) self.assertItemsEqual(modified_tags, ["a new tag 1"]) def test_find_tags_to_be_deleted(self): category_key = self.categories.add("category") other_tags = ["a new tag 3", "a new new tag"] test_existing_tags = ["a new tag", "a new new tag"] editing_tags1 = ["a new tag 1", "a new new tag 2"] editing_tags2 = ["a new tag 1", "a new tag"] # scenario to delete tags "a new tag", non_modified_tags = set(editing_tags1) & set(test_existing_tags) tags_to_be_removed = find_tags_to_be_removed(test_existing_tags, non_modified_tags, other_tags) self.assertItemsEqual(tags_to_be_removed, ["a new tag"]) # scenario to delete all tags non_modified_tags = set(editing_tags1) & set(test_existing_tags) tags_to_be_removed = find_tags_to_be_removed(test_existing_tags, non_modified_tags, []) self.assertItemsEqual(tags_to_be_removed, test_existing_tags) # scenario not to delete any tag tags_to_be_removed = find_tags_to_be_removed(test_existing_tags, [], test_existing_tags) self.assertItemsEqual(tags_to_be_removed, []) def test_find_tags_to_be_added_from_an_edited_post(self): category_key = self.categories.add("category") test_existing_tags = ["a new tag", "a new new tag"] editing_tags1 = ["a new tag 1", "a new new tag 2"] editing_tags2 = ["a new tag 1", "a new tag"] tag_keys = self.tags.add(test_existing_tags) self.posts.add("a title", "body text", category_key, tag_keys) # scenario to add all tags "a new tag", "a new new tag" tags_to_be_added = find_modified_tags(editing_tags1, test_existing_tags) self.assertItemsEqual(tags_to_be_added, editing_tags1) # scenario to add one tag "a new tag 1" tags_to_be_added = find_modified_tags(editing_tags2, test_existing_tags) self.assertItemsEqual(tags_to_be_added, ["a new tag 1"]) # scenario not to delete any tag tags_to_be_added = find_modified_tags(test_existing_tags, test_existing_tags) self.assertItemsEqual(tags_to_be_added, []) def test_edit_post(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post_key = self.posts.add("a title", "body text", category_key, new_tag_keys) post = post_key.get() post.edit("a modified title", "a modified body text", datetime.now(), new_tag_keys, category_key) self.assertEqual("a modified title", post_key.get().title) self.assertEqual("a modified body text", post_key.get().body) self.assertEqual(category_key, post_key.get().category) self.assertItemsEqual(new_tag_keys, post_key.get().tags) def test_get_answers(self): post, _, _, _ = self.create_post_with_answers({ "ans1": True, "ans2": False, "ans3": False }) self.assertItemsEqual(post.get_answers(), [{ u'is_correct': True, u'p_answer': u'ans1' }, { u'is_correct': False, u'p_answer': u'ans2' }, { u'is_correct': False, u'p_answer': u'ans3' }]) def test_edit_post_answers(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post, _, _, _ = self.create_post_with_answers({ "ans1": True, "ans2": False, "ans3": False }) post.edit("a modified title", "a modified body text", datetime.now(), new_tag_keys, category_key, "", raw_answers=[{ u'is_correct': True, u'p_answer': u'ans1' }, { u'is_correct': True, u'p_answer': u'ans2_mod' }, { u'is_correct': False, u'p_answer': u'ans3' }]) self.assertItemsEqual(post.get_answers(), [{ u'is_correct': True, u'p_answer': u'ans1' }, { u'is_correct': True, u'p_answer': u'ans2_mod' }, { u'is_correct': False, u'p_answer': u'ans3' }]) def test_statistics_when_editing_a_post(self): post, category_key, tags_key, _ = self.create_post_with_answers({ "ans1": True, "ans2": False, "ans3": False }) post.set_selected_answer("ans1") post.set_selected_answer("ans1") self.assertEqual(post.get_answers_statistics(), { "Answer": "Selection", u"ans1": 2, u"ans2": 0, u"ans3": 0 }) post.edit("a modified title", "a modified body text", datetime.now(), tags_key, category_key, "", raw_answers=[{ u'is_correct': True, u'p_answer': u'ans1' }, { u'is_correct': True, u'p_answer': u'ans2_mod' }, { u'is_correct': False, u'p_answer': u'ans3' }]) self.assertEqual(post.get_answers_statistics(), { "Answer": "Selection", u"ans1": 2, u"ans2_mod": 0, u"ans3": 0 }) def test_delete_post(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post_key = self.posts.add("a title", "body text", category_key, new_tag_keys) self.posts.delete(post_key) self.assertItemsEqual(self.posts, []) def test_find_tags_to_be_added(self): test_existing_tags = ["a new tag", "a new new tag"] editing_tags = ["a new tag 1", "a new new tag 2"] editing_tags2 = ["a new tag", "a new new tag 2"] non_modified_tags = set(editing_tags) & set(test_existing_tags) tags_to_be_added = find_tags_to_be_added(editing_tags, non_modified_tags, test_existing_tags) # scenario to add all tags "a new tag 1", "a new new tag 2" self.assertItemsEqual(editing_tags, tags_to_be_added) # scenario to add one tag "a new new tag 2" non_modified_tags = set(editing_tags2) & set(test_existing_tags) tags_to_be_added = find_tags_to_be_added(editing_tags2, non_modified_tags, test_existing_tags) self.assertItemsEqual(["a new new tag 2"], tags_to_be_added) def test_to_json_of_posts(self): category_key1 = self.categories.add("category 1") category_key2 = self.categories.add("category 2") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post_key2 = self.posts.add("a new title", "new body text", category_key2, new_tag_keys, "a summary 2") post_key1 = self.posts.add("a title", "body text", category_key1, new_tag_keys, "a summary") post2 = post_key2.get() with open(os.path.join(TEST_IMAGE)) as f: self.assertTrue(post2.add_blob(f.read(), TEST_IMAGE, 'image/jpeg')) with open(os.path.join(TEST_IMAGE2)) as f: self.assertTrue(post2.add_blob(f.read(), TEST_IMAGE2, 'image/jpeg')) json_result = [{ u'body': post_key1.get().body, u'category': post_key1.get().category.get().category, u'updated': datetimeformat(post_key1.get().updated), u'tags': [{ "key": str(new_tag_keys[0]), "val": new_tag_keys[0].get().tag }, { "key": str(new_tag_keys[1]), "val": new_tag_keys[1].get().tag }], u'timestamp': datetimeformat(post_key1.get().timestamp), u'title': post_key1.get().title, u'id': str(post_key1.get().key.id()), u'summary': post_key1.get().summary, u'answers': post_key1.get().answers, u'images': [] }, { u'body': post_key2.get().body, u'category': post_key2.get().category.get().category, u'updated': datetimeformat(post_key2.get().updated), u'tags': [{ "key": str(new_tag_keys[0]), "val": new_tag_keys[0].get().tag }, { "key": str(new_tag_keys[1]), "val": new_tag_keys[1].get().tag }], u'timestamp': datetimeformat(post_key2.get().timestamp), u'title': post_key2.get().title, u'id': str(post_key2.get().key.id()), u'summary': post_key2.get().summary, u'answers': post_key2.get().answers, u'images': [{ u'blob_key': u'encoded_gs_file:YXBwX2RlZmF1bHRfYnVja2V0LzIwMTlfMV80XzE2ei5naWY=', u'filename': TEST_IMAGE }, { u'blob_key': u'encoded_gs_file:YXBwX2RlZmF1bHRfYnVja2V0LzEyXzNfNF8zXzEyei5wbmc=', u'filename': TEST_IMAGE2 }] }] self.assertEqual(json_result, self.posts.to_json()) def test_retrieve_from_memcache(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post_key = self.posts.add("a title", "body text", category_key, new_tag_keys) id = post_key.id() memcached_post = BlogPost.get(id) # requested a post added to MEMCACHE self.assertEqual(memcached_post.key, post_key) def test_get_by_title(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post_key = self.posts.add("a title", "body text", category_key, new_tag_keys) post = self.posts.get_by_title("a title") self.assertEqual(post_key, post.key) def test_get_by_title_assert_raises(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys) # test exception with self.assertRaises(InvalidUsage): self.posts.get_by_title("a non existent title") def test_get_names_from_tags(self): test_tags = ["a new tag", "a new new tag"] self.tags.add(test_tags) self.assertItemsEqual(test_tags, self.tags.get_names()) def test_to_json_of_a_tag(self): test_tags = ["a new tag", "a new new tag"] tag_key1, tag_key2 = self.tags.add(test_tags) tag = tag_key1.get() test_dict = {"id": str(tag_key1.id()), "tag": u"a new tag"} self.assertDictEqual(test_dict, tag.to_json()) def test_to_json_of_tags(self): test_tags = [u"a new tag", u"a new new tag"] tag_key1, tag_key2 = self.tags.add(test_tags) json_data = [{ "id": key, "tag": val } for key, val in zip( [str(tag_key1.id()), str(tag_key2.id())], test_tags)] self.assertListEqual(json_data, self.tags.to_json()) def test_get_a_post(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post_key = self.posts.add("a title", "body text", category_key, new_tag_keys) #test with no memcache post = BlogPost.get(post_key.id()) self.assertEqual(post.key, post_key) #test memcached post = BlogPost.get(post_key.id()) self.assertEqual(post.key, post_key) # def test_filter_posts_by_a_tag(self): # category_key = self.categories.add("category") # test_tags = ["a new tag", "a new new tag"] # new_test_tags = ["a second tag", "a new second tag"] # new_tag_keys = self.tags.add(test_tags) # new_test_tag_keys = self.tags.add(new_test_tags) # post_key = self.posts.add("a title", "body text", category_key, new_tag_keys) # self.posts.add("a title", "a second body text", category_key, new_test_tag_keys ) # print self.posts # self.posts.filter_by_tag("a new tag") # print self.posts, post_key.get() # self.assertItemsEqual(self.posts, [post_key.get()]) # def test_filter_posts_by_category(self): # # post1, _, _, _ = self.create_post_with_answers({"ans1": True, "ans2": False}, category="cat 1") # post2, _, _, _ = self.create_post_with_answers({"ans1": True, "ans2": False}, category="cat 2") # # self.posts.filter_by_category("cat 1") # print self.posts[0], post2 # self.assertItemsEqual(self.posts, [post2]) # # self.posts.filter_by_category("cat 1") # # self.assertItemsEqual(self.posts, [post1]) # # self.posts.filter_by_category("wrong cat") # # self.assertItemsEqual(self.posts, []) def test_get_category(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post_key = self.posts.add("a title", "body text", category_key, new_tag_keys) post = BlogPost.get(post_key.id()) self.assertEqual("category", post.get_category()) def test_get_tagnames(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post_key = self.posts.add("a title", "body text", category_key, new_tag_keys) post = BlogPost.get(post_key.id()) tag_names = post.get_tag_names() self.assertItemsEqual(test_tags, tag_names) def test_posts_contains_a_post(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) post_key = self.posts.add("a title", "body text", category_key, new_tag_keys) self.assertTrue(post_key in self.posts) self.assertFalse("no key" in self.posts) def test_tags_contains_a_tag(self): test_tags = ["a new tag", "a new new tag"] self.tags.add(test_tags) self.assertTrue(test_tags[0] in self.tags) self.assertFalse("dfsd" in self.tags) def test_categories_contains_a_category(self): self.categories.add("category") self.assertTrue("category" in self.categories) self.assertFalse("" in self.categories) # def test_filter_matched(self): # category_key = self.categories.add("category") # test_tags = ["a new tag", "a new new tag"] # new_tag_keys = self.tags.add(test_tags) # post_key = self.posts.add("a title", "body text", category_key, new_tag_keys) # self.posts.add("a title", "body sec2 text", category_key, new_tag_keys) # print self.posts # self.posts.filter_matched([post_key.id()]) # self.assertItemsEqual(self.posts, [post_key.get()]) def test_site_last_updated(self): freezer = freeze_time("2017-11-29 17:48:18") freezer.start() category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) self.posts.add("a title", "body text", category_key, new_tag_keys) self.posts.add("a title", "body sec2 text", category_key, new_tag_keys) last_updated = self.posts.site_last_updated() self.assertEqual("Wednesday 29 November 2017", last_updated) freezer.stop() def test_get_related_posts(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) current_post = self.posts.add("a title", "body text", category_key, new_tag_keys) rel_test_tags = ["a new tag", "a different tag"] rel_tag_keys = self.tags.add(rel_test_tags) rel_post_key = self.posts.add("a different title", "body sec2 text", category_key, rel_tag_keys) rel_post = BlogPost.get(rel_post_key.id()) related_posts = self.posts.get_related_posts(current_post.id()) self.assertListEqual([rel_post], related_posts) def test_update_category(self): category_key = self.categories.add("category") self.categories.update("a modified category", category_key) category = self.categories.get(category_key) self.assertEqual("a modified category", category.category) def test_update_category_without_key(self): category_key = self.categories.update("a modified category") category = self.categories.get(category_key) self.assertEqual("a modified category", category.category) def test_update_tags_without_post(self): test_tags = ["a new tag", "a new new tag"] tag_keys = self.tags.add(test_tags) category_key = self.categories.add("category") self.posts.add("a title", "body text", category_key, tag_keys) test_new_tags = ["a new different tag", "a new new tag"] self.tags.update(test_new_tags) tag_names = self.tags.get_names() self.assertListEqual( tag_names, [u"a new tag", u"a new new tag", u"a new different tag"]) def test_update_tags(self): """ replacing a new tag with a new different tag :return: """ test_tags = ["a new tag", "a new new tag"] tag_keys = self.tags.add(test_tags) category_key = self.categories.add("category") post_key = self.posts.add("a title", "body text", category_key, tag_keys) test_new_tags = ["a new different tag", "a new new tag"] self.tags.update(test_new_tags, BlogPost.get(post_key.id())) tag_names = self.tags.get_names() self.assertListEqual(tag_names, [u"a new new tag", u"a new different tag"]) def test_rebuild_index(self): test_tags = ["a new tag", "a new new tag"] tag_keys = self.tags.add(test_tags) category_key = self.categories.add("category") post_key = self.posts.add("a title", "body text", category_key, tag_keys) self.posts.rebuild_index() results = query_search_index("body") posts_ids = find_posts_from_index(results) self.assertEqual(post_key.id(), posts_ids[0]) def test_add_to_feed(self): test_tags = ["a new tag", "a new new tag"] tag_keys = self.tags.add(test_tags) category_key = self.categories.add("category") self.posts.add("a title", "body text", category_key, tag_keys) feed_org = AtomFeed('Recent Articles', feed_url='http://localhost/recent.atom', url="") feed_model = AtomFeed('Recent Articles', feed_url='http://localhost/recent.atom', url="") for post in self.posts: catname = post.get_category() url = "/".join([ catname, post.timestamp.strftime('%B'), post.timestamp.strftime('%Y') ]) feed_org.add(post.title, post.body, content_type='html', author='Armen Arsakian', url=make_external("http://localhost/recent.atom", url), updated=post.updated, published=post.timestamp) feed = self.posts.add_to_feed(feed_model, "http://localhost/recent.atom") self.assertEqual(feed_org.to_string(), feed.to_string()) def test_stripped_answers(self): test_tags = ["a new tag", "a new new tag"] tag_keys = self.tags.add(test_tags) ans1 = Answer(p_answer="ans1", is_correct=True) ans2 = Answer(p_answer="ans2", is_correct=False) category_key = self.categories.add("category") summary = "a summmary" title = "a title" body = "here is a body" post_key = BlogPost(title=title, body=body, category=category_key, tags=tag_keys, summary=summary, answers=[ans1, ans2]).put() post = post_key.get() jsoned_answers = [{ "p_answer": "ans1", "is_correct": False }, { "p_answer": "ans2", "is_correct": False }] self.assertItemsEqual(post.strip_answers_jsoned(), jsoned_answers) def test_selected_answer_setter(self): post, _, _, _ = self.create_post_with_answers({ "ans1": True, "ans2": False }) ans1 = Answer(p_answer="ans1", is_correct=True) post.set_selected_answer("ans1") self.assertEqual( Answer(is_correct=True, nof_times_selected=1, p_answer=u'ans1', statistics=1.0), post.selected_answer) def test_is_answer_correct(self): post, _, _, _ = self.create_post_with_answers({ "ans1": True, "ans2": False }) post.set_selected_answer("ans1") self.assertTrue(post.is_answer_correct()) post.set_selected_answer('ans2') self.assertFalse(post.is_answer_correct()) post.set_selected_answer('non existent') self.assertFalse(post.is_answer_correct()) def test_to_answer_form(self): post, _, _, _ = self.create_post_with_answers({ "ans1": True, "ans2": False }) self.posts.to_answers_form() self.assertItemsEqual([(u'ans1', u'ans1'), (u'ans2', u'ans2')], post.answers_form.r_answers.choices) def test_update_answers_statistics(self): post, _, _, _ = self.create_post_with_answers({ "ans1": True, "ans2": False }) post.set_selected_answer("ans1") self.assertTupleEqual( (post.answers[0].statistics, post.answers[1].statistics), (1.0, 0.0)) self.assertTupleEqual((post.answers[0].nof_times_selected, post.answers[1].nof_times_selected), (1, 0)) post.set_selected_answer("ans2") self.assertTupleEqual( (post.answers[0].statistics, post.answers[1].statistics), (0.5, 0.5)) self.assertTupleEqual((post.answers[0].nof_times_selected, post.answers[1].nof_times_selected), (1, 1)) post.set_selected_answer("ans2") self.assertAlmostEqual(post.answers[0].statistics, 0.3333, places=4) self.assertAlmostEqual(post.answers[1].statistics, 0.6666666666666666, places=4) self.assertTupleEqual((post.answers[0].nof_times_selected, post.answers[1].nof_times_selected), (1, 2)) def test_get_answers_statistics(self): post, _, _, _ = self.create_post_with_answers({ "ans1": True, "ans2": False, "ans3": False }) post.set_selected_answer("ans1") answers_stats = post.get_answers_statistics() self.assertDictEqual(answers_stats, { "Answer": "Selection", "ans1": 1, "ans2": 0, "ans3": 0 }) post.set_selected_answer("ans2") answers_stats = post.get_answers_statistics() self.assertDictEqual(answers_stats, { "Answer": "Selection", "ans1": 1, "ans2": 1, "ans3": 0 }) answers_stats = post.get_answers_statistics() self.assertDictEqual(answers_stats, { "Answer": "Selection", u"ans1": 1, u"ans2": 1, u"ans3": 0 }) def test_add_blob(self): post, _, _ = self.create_post() with open(os.path.join(TEST_IMAGE)) as f: image_key = post.add_blob(f.read(), TEST_IMAGE, 'image/jpeg') self.assertEqual( image_key, u'encoded_gs_file:YXBwX2RlZmF1bHRfYnVja2V0LzIwMTlfMV80XzE2ei5naWY=' ) def test_delete_blob(self): from google.appengine.ext import blobstore post, _, _ = self.create_post() with open(os.path.join(TEST_IMAGE)) as f: image_key = post.add_blob(f.read(), TEST_IMAGE, 'image/jpeg') post._delete_blob(TEST_IMAGE) with self.assertRaises(blobstore.BlobNotFoundError): blobstore.fetch_data(image_key, 0, 1) def test_read_blob_image(self): post, _, _ = self.create_post() with open(os.path.join(TEST_IMAGE)) as f: post.add_blob(f.read(), TEST_IMAGE, 'image/jpeg') image_file = post.read_blob_image(TEST_IMAGE) f.seek(0) self.assertEqual(image_file, f.read()) def test_list_images(self): post, _, _ = self.create_post() with open(os.path.join(TEST_IMAGE)) as f: post.add_blob(f.read(), TEST_IMAGE, 'image/jpeg') self.assertListEqual(post.list_images(), ['/app_default_bucket/{}'.format(TEST_IMAGE)]) def test_mime_type(self): post, _, _ = self.create_post() with open(os.path.join(TEST_IMAGE)) as f: post.add_blob(f.read(), TEST_IMAGE, 'image/jpeg') self.assertEqual(post.get_mime_type(TEST_IMAGE), 'image/jpeg') def test_delete_image(self): post, _, _ = self.create_post() with open(os.path.join(TEST_IMAGE)) as f: image_key = post.add_blob(f.read(), TEST_IMAGE, 'image/jpeg') post._delete_blob(TEST_IMAGE) with self.assertRaises(cloudstorage.NotFoundError): post.get_blob(image_key) def test_delete_blob_from_post(self): post, _, _ = self.create_post() with open(os.path.join(TEST_IMAGE)) as f: post.add_blob(f.read(), TEST_IMAGE, 'image/jpeg') self.assertEqual(1, len(post.images)) post.delete_blob_from_post(TEST_IMAGE) self.assertEqual(0, len(post.images))
class TestForms(BlogTestBase): def setUp(self): self.testbed = testbed.Testbed() # Then activate the testbed, which prepares the service stubs for use. self.testbed.activate() # Next, enable csrf for proper rendering of forms self.app.config['WTF_CSRF_ENABLED'] = True self.testbed.init_user_stub() self.testbed.init_blobstore_stub() self.testbed.init_datastore_v3_stub() self.testbed.init_app_identity_stub() self.testbed.init_urlfetch_stub() # enable memcache self.testbed.init_memcache_stub() self.categories = Categories() self.tags = Tags() def test_post_form_names(self): form = PostForm() self.assertEqual(form.title.name, 'title') self.assertEqual(form.body.name, 'body') self.assertEqual(form.summary.name, 'summary') self.assertEqual(form.category.name, 'category') self.assertEqual(form.images_upload.name, 'images_upload') self.assertEqual(form.images.name, 'images') def test_hidden_form(self): form = PostForm() out = form.hidden_tag() answer_form = AnswerRadioForm() answer_out = answer_form.hidden_tag() assert (all(x in out for x in ('csrf_token'))) assert (all(x in answer_out for x in ('csrf_token'))) def test_with_data_using_obj(self): category_key = self.categories.add("category") test_tags = ["a new tag", "a new new tag"] new_tag_keys = self.tags.add(test_tags) answer = Answer(p_answer="a test answer", is_correct=False) post = BlogPost(title="a title", body="body text", category=category_key, tags=new_tag_keys, summary="this is a summary", answers=[answer]) post.put() with open(os.path.join(TEST_IMAGE)) as f: self.assertTrue(post.add_blob(f.read(), TEST_IMAGE, 'image/jpeg')) form = PostForm(obj=post) # form.answers.append_entry(answer_field) #print (form.answers) self.assertEqual(form.title.data, "a title") self.assertEqual(form.body.data, "body text") self.assertEqual(form.answers[0].p_answer.data, "a test answer") self.assertEqual(form.images[0].filename.data, TEST_IMAGE) def test_with_data_using_dict(self): class DummyPostData(dict): def getlist(self, key): v = self[key] if not isinstance(v, (list, tuple)): v = [v] return v postdict = DummyPostData({ u'body': u'body text', u'category': u'category', u'updated': 'Monday, 16 April 2018', u'tags': [u'a new tag', u'a new new tag'], u'timestamp': 'Monday, 16 April 2018', u'title': u'a title', u'answers': [{ 'is_correct': False, 'p_answer': u'a test answer' }], u'summary': u'this is a summary', u'id': '4' }) form = PostForm(postdict) form.answers.append_entry([{ 'is_correct': False, 'p_answer': u'a test answer' }]) self.assertEqual(form.title.data, "a title") self.assertEqual(form.body.data, "body text") # self.assertEqual(form.answers[0].p_answer.data, "a test answer") def test_answers_radio_form(self): answers = [("a correct answer", ""), ("a wrong answer", "")] form = AnswerRadioForm() form.r_answers.data = "a test answer" self.assertEqual(form.r_answers.data, "a test answer") def tearDown(self): self.app.config['WTF_CSRF_ENABLED'] = False