def test_validate_account(self): site = Site.objects.get_current().domain user = BlogUser.objects.create_superuser(email="*****@*****.**", username="******", password="******") self.client.login(username='******', password='******') response = self.client.get('/admin/') self.assertEqual(response.status_code, 200) category = Category() category.name = "categoryaaa" category.created_time = datetime.datetime.now() category.last_mod_time = datetime.datetime.now() category.save() article = Article() article.title = "nicetitleaaa" article.body = "nicecontentaaa" article.author = user article.category = category article.type = 'a' article.status = 'p' article.save() response = self.client.get(article.get_admin_url()) self.assertEqual(response.status_code, 200)
def test_edit_category(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Log in self.client.login(username='******', password="******") # Edit the category response = self.client.post( '/admin/blog/category/1/', { 'name': 'perl', 'description': 'The Perl programming language' }, follow=True) self.assertEquals(response.status_code, 200) # Check modificado com sucesso self.assertTrue('modificado com sucesso' in response.content) # Check category amended all_categories = Category.objects.all() self.assertEquals(len(all_categories), 1) only_category = all_categories[0] self.assertEquals(only_category.name, 'perl') self.assertEquals(only_category.description, 'The Perl programming language')
def test_creating_a_new_comment_and_saving_it_to_the_database(self): # start by create one Category and one post category = Category() category.name = "First" category.slug = "first" category.save() # create new post post = Post() post.category = category post.title = "First post" post.content = "Content" post.visable = True post.save() # create one comment comment = Comment() comment.name = "John" comment.content = "This is cool" comment.post = post # check save comment.save() # now check we can find it in the database all_comment_in_database = Comment.objects.all() self.assertEquals(len(all_comment_in_database), 1) only_comment_in_database = all_comment_in_database[0] self.assertEquals(only_comment_in_database, comment) # and check that it's saved its two attributes: name and content self.assertEquals(only_comment_in_database.name, comment.name) self.assertEquals(only_comment_in_database.content, comment.content)
def __create_category(self, lang, title, desc): cat = Category(lang=lang, title=title, desc=desc) cat.save() print("Created category : {} | {} | {} | ".format(lang, title, desc)) return cat
def test_validate_comment(self): site = Site.objects.get_current().domain user = BlogUser.objects.create_superuser(email="*****@*****.**", username="******", password="******") self.client.login(username='******', password='******') c = Category() c.name = "categoryccc" c.created_time = datetime.datetime.now() c.last_mod_time = datetime.datetime.now() c.save() article = Article() article.title = "nicetitleccc" article.body = "nicecontentccc" article.author = user article.category = c article.type = 'a' article.status = 'p' article.save() s = TextMessage([]) s.content = "nicetitleccc" rsp = search(s, None) self.assertTrue(rsp != '没有找到相关文章。') rsp = category(None, None) self.assertIsNotNone(rsp) rsp = recents(None, None) self.assertTrue(rsp != '暂时还没有文章') cmd = commands() cmd.title = "test" cmd.command = "ls" cmd.describe = "test" cmd.save() cmdhandler = CommandHandler() rsp = cmdhandler.run('test') self.assertIsNotNone(rsp) s.source = 'u' s.content = 'test' msghandler = MessageHandler(s, {}) #msghandler.userinfo.isPasswordSet = True #msghandler.userinfo.isAdmin = True msghandler.handler() s.content = 'y' msghandler.handler() s.content = 'idcard:12321233' msghandler.handler() s.content = 'weather:上海' msghandler.handler() s.content = 'admin' msghandler.handler() s.content = '123' msghandler.handler() s.content = 'exit' msghandler.handler()
def test_creating_a_new_post_and_saving_it_to_the_database(self): # start by create one Category category = Category() category.name = "First" category.slug = "first" category.save() # create new post post = Post() post.category = category post.title = "First post" post.content = "Content" post.visable = True # check we can save it post.save() # check slug self.assertEquals(post.slug, "first-post") # now check we can find it in the database all_post_in_database = Post.objects.all() self.assertEquals(len(all_post_in_database), 1) only_post_in_database = all_post_in_database[0] self.assertEquals(only_post_in_database, post) # check that it's saved all attributes: category, title, content, visable and generate slug self.assertEquals(only_post_in_database.category, category) self.assertEquals(only_post_in_database.title, post.title) self.assertEquals(only_post_in_database.content, post.content) self.assertEquals(only_post_in_database.visable, post.visable) self.assertEquals(only_post_in_database.slug, post.slug)
def test_validate_article(self): from accounts.models import BlogUser site = Site.objects.get_current().domain user = BlogUser() user.email = "*****@*****.**" user.username = "******" user.password = "******" user.set_password("liangliangyy") user.save() response = self.client.get(user.get_absolute_url()) self.assertEqual(response.status_code, 200) category = Category() category.name = "category" category.created_time = datetime.datetime.now() category.last_mod_time = datetime.datetime.now() category.save() response = self.client.get(category.get_absolute_url()) self.assertEqual(response.status_code, 200) article = Article() article.title = "nicetitle" article.body = "nicecontent" article.author = user article.category = category article.type = 'a' article.status = 'p' article.save() response = self.client.get(article.get_absolute_url()) self.assertEqual(response.status_code, 200)
def blog_index(request): run_check() posts = Post.objects.all().order_by('-created_on') form = PostForm() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): a = form.cleaned_data['cat'] count = Category.objects.filter(name=a).count() post = Post( writer=request.user, body=form.cleaned_data['body'], title=form.cleaned_data['title'], ) if count == 0: ct = Category(name=form.cleaned_data['cat']) ct.save() else: ct = Category.objects.get(name=a) post.save() post.categories.add(ct) context = { "posts": posts, 'form': form, 'user': request.user, } return render(request, "blog_index.html", context)
def test_create_post_without_tag(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Log in self.client.login(username='******', password="******") # Check response code response = self.client.get('/admin/blog/post/add/') self.assertEquals(response.status_code, 200) # Create the new post response = self.client.post('/admin/blog/post/add/', { 'title': 'My first post', 'text': 'This is my first post', 'pub_date_0': '2013-12-28', 'pub_date_1': '22:00:04', 'slug': 'my-first-post', # 'site': '1', 'category': '1' }, follow=True ) self.assertEquals(response.status_code, 200) # Check added successfully self.assertTrue('added successfully' in response.content) # Check new post now in database all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1)
class PostTests(TestCase): def setUp(self): self.author = Consumer.objects.create_user( email="*****@*****.**", password="******" ) self.category = Category(title="Test Category", slug="test-category") self.post = Post( title="This is a test", slug="this-is-a-test", author=self.author, category=self.category, content="this is a test content", status=0, ) self.author.save() self.category.save() self.post.save() def test_post_creation(self): self.assertEqual(len(Category.objects.all()), 1) self.assertEqual(len(Post.objects.all()), 1) self.assertEqual(self.post.status, 0) def test_post_changing_status(self): Post.objects.change_status(self.post.pk, 1) post = Post.objects.get(pk=1) self.assertEqual(post.status, 1)
def test_edit_category(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Log in self.client.login(username='******', password="******") # Edit the category response = self.client.post('/admin/blogengine/category/1/', { 'name': 'perl', 'description': 'The Perl programming language' }, follow=True) self.assertEquals(response.status_code, 200) # Check changed successfully self.assertTrue('changed successfully' in response.content) # Check category amended all_categories = Category.objects.all() self.assertEquals(len(all_categories), 1) only_category = all_categories[0] self.assertEquals(only_category.name, 'perl') self.assertEquals(only_category.description, 'The Perl programming language')
def handle(self, *args, **options): with open('upload-temp') as f: sep = '\n' + ('-' * 70) + '\n' fields = f.read().split(sep) if options['edit']: try: p = Post.objects.get(slug=fields[1]) p.edited = datetime.now() except Post.DoesNotExist: raise CommandError('no post with slug "%s" exists' % fields[1]) else: p = Post() p.created = datetime.now() p.edited = None p.title = fields[0] p.slug = fields[1] p.preview = fields[3] p.content = fields[4] p.save() p.categories.clear() for cat in fields[2].split(', '): try: c = Category.objects.get(name=cat) except Category.DoesNotExist: c = Category(name=cat, slug=slugify(cat)) c.save() p.categories.add(c) p.save()
def async_add_category(request): if not request.POST: raise Http404 data = {} name = request.POST.get('name', False) slug = request.POST.get('slug', False) if name == False or slug == False: data.update({"status": False, "message": "Invalid data."}) elif len(name) == 0 or len(slug) == 0: data.update({"status": False, "message": "Neither field can be blank."}) else: try: cat = Category(name=slug,label=name) # Stupid naming of the model. Don't feel like fixing all references.. cat.save() data.update({"status": True, "message": "Category successfully added.", "slug": cat.name, "name": cat.label}) except: data.update({"status": False, "message": "An unknown error occured. Please reload the page."}) return HttpResponse(simplejson.dumps(data), mimetype="application/javascript") ### END AJAX VIEWS ###
def test_validate_account(self): site = get_current_site().domain user = BlogUser.objects.create_superuser( email="*****@*****.**", username="******", password="******") testuser = BlogUser.objects.get(username='******') loginresult = self.client.login(username='******', password='******') self.assertEqual(loginresult, True) response = self.client.get('/admin/') self.assertEqual(response.status_code, 200) category = Category() category.name = "categoryaaa" category.created_time = datetime.datetime.now() category.last_mod_time = datetime.datetime.now() category.save() article = Article() article.title = "nicetitleaaa" article.body = "nicecontentaaa" article.author = user article.category = category article.type = 'a' article.status = 'p' article.save() response = self.client.get(article.get_admin_url()) self.assertEqual(response.status_code, 200)
def post(self): from .models import FontIcon, FontIconLibrary iconclass = None i = request.form.get('icon', None) if i is not None: lib, icon = i.split('-')[0], i.split('-')[1:] iconclass = FontIcon.query.filter( FontIcon.name == ''.join(map(str, icon)), FontIconLibrary.name == lib).first() self._context['form_args'] = {'heading': self._form_heading} self._form = self._form(request.form) if self._form.validate(): from blog.models import Category c = Category.query.filter( Category.name == self._form.name.data).first() if c is None: c = Category() if iconclass is not None: c.icon_id = iconclass.id c.name = self._form.name.data c.description = self._form.description.data c.save() self.flash('You added category: {}'.format(c.name)) if request.args.get('last_url'): return self.redirect(request.args.get('last_url'), raw=True) else: self.flash( 'There is already a category by that name, try again') return self.redirect('core.index')
def test_create_post_without_tag(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Log in self.client.login(username='******', password="******") # Check response code response = self.client.get('/admin/blog/post/add/') self.assertEquals(response.status_code, 200) # Create the new post response = self.client.post('/admin/blog/post/add/', { 'title': 'My first post', 'text': 'This is my first post', 'pub_date_0': '2013-12-28', 'pub_date_1': '22:00:04', 'slug': 'my-first-post', 'site': '1', 'category': '1' }, follow=True) self.assertEquals(response.status_code, 200) # Check added successfully self.assertTrue('adicionado com sucesso' in response.content) # Check new post now in database all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1)
def addCategory(request): if request.method=='POST': name = request.POST['name'] slug = request.POST['slug'] desc = request.POST['desc'] type = request.POST['type'] if type and type == 'add': try: cats=Category.objects.filter(name=name) if cats.count() >= 1: messages.add_message(request,messages.INFO,'categry [%s] already exits!'%(name)) else: cat = Category(name=name,slug=slug,desc=desc) cat.save() messages.add_message(request,messages.INFO,'categry [%s] save ok!'%(name)) except: pass elif type and type == 'edit': id = request.POST.get('id','') cat = Category.objects.get(id=id) cat.name=name cat.slug=slug cat.desc=desc cat.save() return HttpResponseRedirect('/admin/categories')
def addCategory(request): name = request.POST['name'] slug = request.POST['slug'] desc = request.POST['desc'] type = request.POST['type'] pid = request.POST['category_parent'] if pid == '0': pid = None if type and type == 'add': try: cats=Category.objects.filter(name=name) if cats.count() >= 1: messages.add_message(request,messages.INFO,'categry [%s] already exits!'%(name)) else: cat = Category(name=name,slug=slug,desc=desc,parent_id=pid) cat.save() messages.add_message(request,messages.INFO,'categry [%s] save ok!'%(name)) except Exception as e: print 'exception:',e elif type and type == 'edit': id = request.POST.get('id','') cat = Category.objects.get(id=id) cat.name=name cat.slug=slug cat.desc=desc cat.parent_id = pid cat.save() return HttpResponseRedirect('/admin/categories')
def post(self): from .models import FontIcon,FontIconLibrary iconclass = None i = request.form.get('icon',None) if i is not None: lib,icon = i.split('-')[0],i.split('-')[1:] iconclass = FontIcon.query.filter(FontIcon.name==''.join(map(str,icon)),FontIconLibrary.name==lib).first() self._context['form_args'] = {'heading':self._form_heading} self._form = self._form(request.form) if self._form.validate(): from blog.models import Category c = Category.query.filter(Category.name==self._form.name.data).first() if c is None: c = Category() if iconclass is not None: c.icon_id = iconclass.id c.name = self._form.name.data c.description = self._form.description.data c.save() self.flash('You added category: {}'.format(c.name)) if request.args.get('last_url'): return self.redirect(request.args.get('last_url'),raw=True) else: self.flash('There is already a category by that name, try again') return self.redirect('core.index')
def test_validate_register(self): self.assertEquals( 0, len(BlogUser.objects.filter(email='*****@*****.**'))) response = self.client.post( reverse('account:register'), { 'username': '******', 'email': '*****@*****.**', 'password1': 'password123!q@wE#R$T', 'password2': 'password123!q@wE#R$T', }) self.assertEquals( 1, len(BlogUser.objects.filter(email='*****@*****.**'))) user = BlogUser.objects.filter(email='*****@*****.**')[0] sign = get_md5(get_md5(settings.SECRET_KEY + str(user.id))) path = reverse('accounts:result') url = '{path}?type=validation&id={id}&sign={sign}'.format(path=path, id=user.id, sign=sign) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.client.login(username='******', password='******') user = BlogUser.objects.filter(email='*****@*****.**')[0] user.is_superuser = True user.is_staff = True user.save() delete_sidebar_cache(user.username) category = Category() category.name = "categoryaaa" category.created_time = datetime.datetime.now() category.last_mod_time = datetime.datetime.now() category.save() article = Article() article.category = category article.title = "nicetitle333" article.body = "nicecontentttt" article.author = user article.type = 'a' article.status = 'p' article.save() response = self.client.get(article.get_admin_url()) self.assertEqual(response.status_code, 200) response = self.client.get(reverse('account:logout')) self.assertIn(response.status_code, [301, 302, 200]) response = self.client.get(article.get_admin_url()) self.assertIn(response.status_code, [301, 302, 200]) response = self.client.post(reverse('account:login'), { 'username': '******', 'password': '******' }) self.assertIn(response.status_code, [301, 302, 200]) response = self.client.get(article.get_admin_url()) self.assertIn(response.status_code, [301, 302, 200])
def handle(self, *args, **options): self.stdout.write('wait a second..') fake = Factory.create('zh_CN') iamge_base = settings.QINIU_BASE_URL + 'fake_site/' for i in range(1, 4): c = Category(id=i, name='test category {0}'.format(i)) c.save() tags = [] for i in range(20): tags.append(fake.city()) tags = set(tags) for i in range(50): p = Post( category=Category.objects.get(pk=randint(1, 3)), header_image_url=iamge_base + '{}.jpg'.format(randint(1, 5)), title=fake.country() + fake.city_name() + fake.street_name(), subtitle=fake.sentence(nb_words=2, variable_nb_words=True), content=self.fake_markdown_content(fake)) p.save() p.tags.add(*sample(tags, randint(1, 3))) orginal = p.create_date p.create_date = orginal.replace(year=randint(2013, 2015), month=randint(1, 12)) p.save() user = User.objects.create_user('demouser', password='******') user.save() self.stdout.write(self.style.SUCCESS('done!')) self.stdout.write(self.style.SUCCESS('username as password: demouser'))
def test_all_post_feed(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() # Create the author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create a post post = Post() post.title = 'My first post' post.text = 'This is my first blog post' post.slug = 'my-first-post' post.pub_date = timezone.now() post.author = author post.site = site post.category = category # Save it post.save() # Add the tag post.tags.add(tag) post.save() # Check we can find it all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) # Fetch the feed response = self.client.get('/feeds/posts/') self.assertEquals(response.status_code, 200) # Parse the feed feed = feedparser.parse(response.content) # Check length self.assertEquals(len(feed.entries), 1) # Check post retrieved is the correct one feed_post = feed.entries[0] self.assertEquals(feed_post.title, post.title) self.assertEquals(feed_post.description, post.text)
def test_category_page(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Create the author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() post.title = 'My first post' post.text = 'This is [my first blog post](http://127.0.0.1:8000/)' post.slug = 'my-first-post' post.pub_date = timezone.now() post.author = author post.site = site post.category = category post.save() # Check new post saved all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) # Get the category URL category_url = post.category.get_absolute_url() # Fetch the category response = self.client.get(category_url) self.assertEquals(response.status_code, 200) # Check the category name is in the response self.assertTrue(post.category.name in response.content) # Check the post text is in the response self.assertTrue( markdown.markdown(post.text).encode() in response.content) # Check the post date is in the response self.assertTrue(str(post.pub_date.year) in response.content) self.assertTrue( _date(post.pub_date, "F").encode('utf-8') in response.content) self.assertTrue(str(post.pub_date.day) in response.content) # Check the link is marked up properly self.assertTrue( '<a href="http://127.0.0.1:8000/">my first blog post</a>' in response.content)
def test_validate_comment(self): site = Site.objects.get_current().domain user = BlogUser.objects.create_superuser(email="*****@*****.**", username="******", password="******") self.client.login(username='******', password='******') c = Category() c.name = "categoryccc" c.created_time = datetime.datetime.now() c.last_mod_time = datetime.datetime.now() c.save() article = Article() article.title = "nicetitleccc" article.body = "nicecontentccc" article.author = user article.category = c article.type = 'a' article.status = 'p' article.save() s = TextMessage([]) s.content = "nicetitleccc" rsp = search(s, None) self.assertTrue(rsp != '没有找到相关文章。') rsp = category(None, None) self.assertIsNotNone(rsp) rsp = recents(None, None) self.assertTrue(rsp != '暂时还没有文章') cmd = commands() cmd.title = "test" cmd.command = "ls" cmd.describe = "test" cmd.save() cmdhandler = CommandHandler() rsp = cmdhandler.run('test') self.assertIsNotNone(rsp) s.source = 'u' s.content = 'test' msghandler = MessageHandler(s, {}) #msghandler.userinfo.isPasswordSet = True #msghandler.userinfo.isAdmin = True msghandler.handler() s.content = 'y' msghandler.handler() s.content='idcard:12321233' msghandler.handler() s.content='weather:上海' msghandler.handler() s.content='admin' msghandler.handler() s.content='123' msghandler.handler() s.content = 'exit' msghandler.handler()
def createCategory(request): if request.method == 'GET': return render(request, 'createcategory.html') else: t = request.POST['category'] c = Category(title=t) c.save() return redirect('home')
def post(self, request): try: name = request.POST.get('name') description = request.POST.get('description') category = Category(name=name, description=description) category.save() except Exception, e: return JsonResponse({'msg': '新增失败\n%s' % unicode(e)}, status=500)
def __create_category(self, lang, title, desc): cat = Category(lang=lang, title=title, desc=desc) cat.save() print( "Created category : {} | {} | {} | ".format(lang, title, desc)) return cat
def save_category(category_id): category = None try: category = Category.objects.get(name=category_id) except Exception: pass if not category: category = Category(name=category_id) category.save()
def test_is_count_one(self): category = Category(name="テストカテゴリー") category.save() tag = Tag(name="テストタグ") tag.save() post = Post(category=category, title="test_title", body="test_body") post.save() saved_posts = Post.objects.all() self.assertEqual(saved_posts.count(), 1)
def test_edit_posts(self): category = Category() category.name = 'python' category.description = 'The python language' category.save() # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # site = Site() # site.name = 'nunfuxgvn.com' # site.domain = 'nunfuxgvn.com' # site.save() post = Post() post.title = 'First Post' post.content = 'My first post -yay' post.slug = 'first-post' post.pub_date = timezone.now() post.author = author # post.site = site post.save() post.tags.add(tag) post.save() self.client.login(username='******', password='******') response = self.client.post('/admin/blog/post/1/', { 'title': 'Second Post', 'text': 'This is my second post', 'pub_date_0': '2014-07-17', 'pub_date_1': '11:49:24', 'slug': 'second-post', # 'site': '1', 'category': '1', 'tags': '1' }, follow=True ) self.assertEquals(response.status_code, 200) # Check post successfully changed self.assertTrue('changed successfully' in response.content) # Check post amended all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post.title, 'Second Post') self.assertEquals(only_post.content, 'This is my second post')
def add_category(request): try: req = convertRequest(request) category_name = req['category_name'] category = Category(category_name=category_name) category.save() return HttpResponse(response_json.success()) except Exception, e: return HttpResponse(response_json.fail(traceback.format_exc()))
def test_delete_post(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() # Create the author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() post.title = 'My first post' post.text = 'This is my first blog post' post.slug = 'my-first-post' post.pub_date = timezone.now() post.site = site post.author = author post.save() post.tags.add(tag) post.save() # Check new post saved all_posts = Post.objects.all() self.assertGreater(len(all_posts), 0) # Log in self.client.login(username='******', password="******") # Delete the post response = self.client.post('/admin/blog/post/1/delete/', {'post': 'yes'}, follow=True) self.assertEquals(response.status_code, 200) # Check excluído com sucesso self.assertTrue('excluído com sucesso' in response.content) # Check post amended all_posts = Post.objects.all() self.assertEquals(len(all_posts), 0)
def test_delete_post(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() # Create the author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() post.title = 'My first post' post.text = 'This is my first blog post' post.slug = 'my-first-post' post.pub_date = timezone.now() post.site = site post.author = author post.category = category post.save() post.tags.add(tag) post.save() # Check new post saved all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) # Log in self.client.login(username='******', password="******") # Delete the post response = self.client.post('/admin/blogengine/post/1/delete/', { 'post': 'yes' }, follow=True) self.assertEquals(response.status_code, 200) # Check deleted successfully self.assertTrue('deleted successfully' in response.content) # Check post deleted all_posts = Post.objects.all() self.assertEquals(len(all_posts), 0)
def post(self, request, *args, **kwargs): # name = request.Post.get('name') # description = request.Post.get('description') 这种用法不正确 # request.data 返回解析之后的请求体数据 name = request.data['name'] description = request.data['description'] category_obj = Category(name=name, description=description) category_obj.save() return Response('添加文章类型成功')
def test_category_page(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Create the author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() post.title = 'My first post' post.text = 'This is [my first blog post](http://127.0.0.1:8000/)' post.slug = 'my-first-post' post.pub_date = timezone.now() post.author = author post.site = site post.category = category post.save() # Check new post saved all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) # Get the category URL category_url = post.category.get_absolute_url() # Fetch the category response = self.client.get(category_url) self.assertEquals(response.status_code, 200) # Check the category name is in the response self.assertTrue(post.category.name in response.content) # Check the post text is in the response self.assertTrue(markdown.markdown(post.text) in response.content) # Check the post date is in the response self.assertTrue(str(post.pub_date.year) in response.content) self.assertTrue(post.pub_date.strftime('%b') in response.content) self.assertTrue(str(post.pub_date.day) in response.content) # Check the link is marked up properly self.assertTrue('<a href="http://127.0.0.1:8000/">my first blog post</a>' in response.content)
def add_new_category(request): if request.method == 'POST': text = request.POST.get('text') slug = request.POST.get('slug') category = Category() category.text = text category.slug = slug category.save() my_dict = {'taxonomy':'category'} return render(request, 'backend/taxonomy.html', context=my_dict)
def add_category(request): """添加分类""" category_name = request.POST.get('category_name') if category_name is None or len(category_name) < 1 or len( category_name) > 20: return HttpResponseBadRequest() category = Category(category_name=category_name) category.save() return HttpResponseRedirect('/backend/categories')
def test_validate_register(self): self.assertEquals( 0, len(BlogUser.objects.filter(email='*****@*****.**'))) response = self.client.post( reverse('account:register'), { 'username': '******', 'email': '*****@*****.**', 'password1': 'password123!q@wE#R$T', 'password2': 'password123!q@wE#R$T', }) self.assertEquals( 1, len(BlogUser.objects.filter(email='*****@*****.**'))) self.client.login(username='******', password='******') user = BlogUser.objects.filter(email='*****@*****.**')[0] user.is_superuser = True user.is_staff = True user.save() delete_view_cache(user.username) category = Category() category.name = "categoryaaa" category.created_time = datetime.datetime.now() category.last_mod_time = datetime.datetime.now() category.save() article = Article() article.category = category article.title = "nicetitle333" article.body = "nicecontentttt" article.author = user article.type = 'a' article.status = 'p' article.save() response = self.client.get(article.get_admin_url()) self.assertEqual(response.status_code, 200) response = self.client.get(reverse('account:logout')) self.assertIn(response.status_code, [301, 302, 200]) response = self.client.get(article.get_admin_url()) self.assertIn(response.status_code, [301, 302, 200]) response = self.client.post(reverse('account:login'), { 'username': '******', 'password': '******' }) self.assertIn(response.status_code, [301, 302, 200]) response = self.client.get(article.get_admin_url()) self.assertIn(response.status_code, [301, 302, 200])
def test_validate_comment(self): site = get_current_site().domain user = BlogUser.objects.create_superuser( email="*****@*****.**", username="******", password="******") self.client.login(username='******', password='******') c = Category() c.name = "categoryccc" c.created_time = timezone.now() c.last_mod_time = timezone.now() c.save() article = Article() article.title = "nicetitleccc" article.body = "nicecontentccc" article.author = user article.category = c article.type = 'a' article.status = 'p' article.save() s = TextMessage([]) s.content = "nice" rsp = search(s, None) rsp = category(None, None) self.assertIsNotNone(rsp) rsp = recents(None, None) self.assertTrue(rsp != 'No articles yet') cmd = commands() cmd.title = "test" cmd.command = "ls" cmd.describe = "test" cmd.save() cmdhandler = CommandHandler() rsp = cmdhandler.run('test') self.assertIsNotNone(rsp) s.source = 'u' s.content = 'test' msghandler = MessageHandler(s, {}) # msghandler.userinfo.isPasswordSet = True # msghandler.userinfo.isAdmin = True msghandler.handler() s.content = 'y' msghandler.handler() s.content = 'idcard:12321233' msghandler.handler() s.content = 'weather:
def test_index(self): category = Category() category.name = 'python' category.description = 'The python language' category.save() # Create the tag tag = Tag() tag.name = 'perl' tag.description = 'The Perl programming language' tag.save() author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # site = Site() # site.name = 'nunfuxgvn.com' # site.domain = 'nunfuxgvn.com' # site.save() post = Post() post.title = 'First Post' post.content = 'My [first post](http://127.0.0.1:8000/) -yay' post.slug = 'first-post' post.pub_date = timezone.now() post.author = author # post.site = site post.category = category post.save() post.tags.add(tag) all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) # Fetch test_index response = self.client.get('/') self.assertEquals(response.status_code, 200) self.assertTrue(post.title in response.content) self.assertTrue(markdown.markdown(post.content) in response.content) self.assertTrue(post.category.name in response.content) post_tag = all_posts[0].tags.all()[0] self.assertTrue(post_tag.name in response.content) self.assertTrue(str(post.pub_date.year) in response.content) self.assertTrue(post.pub_date.strftime('%b') in response.content) self.assertTrue(str(post.pub_date.day) in response.content) self.assertTrue('<a href="http://127.0.0.1:8000/">first post</a>' in response.content)
def addCategory(fatherid, name): father = Category.objects.get(id=fatherid) if fatherid != 1: pathStr = father.pathStr + "#" + name else: pathStr = name newCategory = Category( name=name, fatherid=fatherid, pathStr=pathStr, cnt=0, ) newCategory.save()
def test_saving_retrieving_post(self): category = Category(name="テストカテゴリー") category.save() tag = Tag(name="テストタグ") tag.save() post = Post(category=category, title="test_title", body="test_body") post.save() saved_posts = Post.objects.all() actual_post = saved_posts[ 0] #0は、saved_postsというリストから最初の値を取り出すという意味。2番目の値を取り出すなら1 self.assertEqual(actual_post.title, "test_title") self.assertEqual(actual_post.body, "test_body")
def blog_list_categories(request): form = AddCategory() if request.method == 'POST': form = AddCategory(request.POST) if form.is_valid(): category = Category( name=form.cleaned_data["name"], ) category.save() categories = Category.objects.all() context = {"categories":categories, "form":form} return render(request, "blog_list_categories.html", context=context)
def savepost(request): c = Category(name='category test') c.save() t = Tag(name='tag1') t.save() user = User.objects.get(username='******') p = Post(title='title test', body='body test', created_time=timezone.now(), modified_time=timezone.now(), category=c, author=user) p.save() return HttpResponse('<P>添加数据成功</P>')
def test_delete_url(self): category = Category(name="テストカテゴリー") category.save() tag = Tag(name="テストタグ") tag.save() post = Post(category=category, title="test_title", body="test_body") post.save() url = reverse("blog:delete", kwargs={"pk": post.pk}) response = self.client.get(url) self.assertEqual(response.status_code, 200) template = "blog/post_comfirm_delete.html" self.assertTemplateUsed(template)
def post(self): self._context['form_args'] = {'heading':self._form_heading} self._form = self._form(request.form) if self._form.validate(): from blog.models import Category c = Category.query.filter(Category.name==self._form.name.data).first() if c is None: c = Category() c.name = self._form.name.data c.description = self._form.description.data c.save() self.flash('You added category: {}'.format(c.name)) else: self.flash('There is already a category by that name, try again') return self.render()
def test_validate_register(self): self.assertEquals(0, len(BlogUser.objects.filter(email='*****@*****.**'))) response = self.client.post(reverse('account:register'), { 'username': '******', 'email': '*****@*****.**', 'password1': 'password123', 'password2': 'password123', }) self.assertEquals(1, len(BlogUser.objects.filter(email='*****@*****.**'))) self.client.login(username='******', password='******') user = BlogUser.objects.filter(email='*****@*****.**')[0] user.is_superuser = True user.is_staff = True user.save() category = Category() category.name = "categoryaaa" category.created_time = datetime.datetime.now() category.last_mod_time = datetime.datetime.now() category.save() article = Article() article.category = category article.title = "nicetitle333" article.body = "nicecontentttt" article.author = user article.type = 'a' article.status = 'p' article.save() response = self.client.get(article.get_admin_url()) self.assertEqual(response.status_code, 200) response = self.client.get(reverse('account:logout')) self.assertIn(response.status_code, [301, 302]) response = self.client.get(article.get_admin_url()) self.assertIn(response.status_code, [301, 302]) response = self.client.post(reverse('account:login'), { 'username': '******', 'password': '******' }) self.assertIn(response.status_code, [301, 302]) response = self.client.get(article.get_admin_url()) self.assertEqual(response.status_code, 200)
def add(request): uid = int(-1) userInfos = common.Users(request, uid) currentUser = userInfos["currentuser"] name = utility.GetPostData(request, "name") sortnum = utility.GetPostData(request, "sortnum") if request.POST.has_key("ok"): categoryInfo = Category() categoryInfo.name = name categoryInfo.sortnum = sortnum categoryInfo.user_id = currentUser.id categoryInfo.save() return HttpResponseRedirect(categoryroot % currentUser.id)
def addCategory(request): categories=Category.objects.all(); addCategory=True; displayForm=True; if request.method=='POST': form=CategoryForm(request.POST) if form.is_valid(): title=form.cleaned_data['title']; envoi=True #creation of the section object category=Category(title=title) category.save(); return home(request) else: form=CategoryForm() return render(request, 'blog/blogForm.html',locals())
def new_post(request): """ Create a new Post """ if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): #Separate the tags we have seen before from those we haven't tags = form.cleaned_data['tags'].split(' ') known_tags = list(Tag.objects.filter(tag__in=tags)) unknown_tag_names = set(tags) - set(x.tag for x in known_tags) #Create the unknown tags unknown_tags = [Tag(tag=x) for x in unknown_tag_names] #Tag.objects.bulk_create(unknown_tags) # Sadly, this doesn't work. [t.save() for t in unknown_tags] #If category doesn't exist, create it try: category = Category.objects.get(name=form.cleaned_data['category']) except Category.DoesNotExist: category = Category(name=form.cleaned_data['category'], description='') category.save() #Create the Post object post = Post( user = request.user, category = category, title = form.cleaned_data['title'], body = form.cleaned_data['body'], date = datetime.now() ) post.save() #You must create a primary key (by saving an object), #before you can use a many to many relationship post.tags.add(*(known_tags + unknown_tags)) post.save() return HttpResponseRedirect('/') else: messages.error(request, 'Invalid post') return HttpResponseRedirect(reverse('new_post')) else: form = PostForm() return render(request, 'new_post.html', { 'form': form, })
def test_create_category(self): category = Category() category.name = 'python' category.description = 'The python language' category.slug = 'python' category.save() all_categories = Category.objects.all() self.assertEquals(len(all_categories), 1) only_category = all_categories[0] self.assertEquals(only_category, category) self.assertEquals(only_category.name, 'python') self.assertEquals(only_category.description, 'The python language') self.assertEquals(only_category.slug, 'python')
def init_data(**kwargs): link=Link(text="dengmin's blog",href="http://www.iyouf.info") link.save() default_cate=Category(name=u'未分类',slug='default',desc=u'未分类') default_cate.save() entry=Entry(title='Hello World!',content='<b>Hello World, welcome to use youflog! thank you!</a>',tags='youflog') entry.allow_comment=True entry.slug='hello-world' entry.category=default_cate entry.author_id=1 entry.save(True) comment=Comment(author='admin',email='*****@*****.**',weburl='http://iyouf.info',content=u'测试第一条评论') comment.content_object=entry comment.save()
def test_delete_post(self): category = Category() category.name = 'python' category.description = 'The python language' category.save() # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # site = Site() # site.name = 'nunfuxgvn.com' # site.domain = 'nunfuxgvn.com' # site.save() post = Post() post.title = 'First Post' post.test = 'My first post' post.slug = 'first-post' post.pub_date = timezone.now() post.author = author # post.site = site post.save() post.tags.add(tag) post.save() all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) self.client.login(username='******', password='******') response = self.client.post('/admin/blog/post/1/delete/', { 'post': 'yes' }, follow=True) self.assertEquals(response.status_code, 200) self.assertTrue('deleted successfully' in response.content) all_posts = Post.objects.all() self.assertEquals(len(all_posts), 0)
def test_unique_slug_generate(self): # start by create one Category category = Category() category.name = "First" category.slug = "first" category.save() # create new posts post1 = Post(category=category, title="First post", content="Content", visable=True) post1.save() post2 = Post(category=category, title="First post", content="Content", visable=True) post2.save() # check posts then it's the same title self.assertEquals(post1.title, post2.title) # and different slug self.assertNotEquals(post1.slug, post2.slug)
def test_creating_a_new_category_and_saving_it_to_the_database(self): # start by createing a new Category object category = Category() category.name = "First" category.slug = "first" # check we can save it to the database category.save() # now check we can find it in the database again all_category_in_database = Category.objects.all() self.assertEquals(len(all_category_in_database), 1) only_category_in_database = all_category_in_database[0] self.assertEquals(only_category_in_database, category) # and check that it's saved its two attributes: name and slug self.assertEquals(only_category_in_database.name, category.name) self.assertEquals(only_category_in_database.slug, category.slug)
def test_delete_category(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Log in self.client.login(username='******', password="******") # Delete the category response = self.client.post('/admin/blogengine/category/1/delete/', { 'post': 'yes' }, follow=True) self.assertEquals(response.status_code, 200) # Check deleted successfully self.assertTrue('deleted successfully' in response.content) # Check category deleted all_categories = Category.objects.all() self.assertEquals(len(all_categories), 0)
def test_create_category(self): # Create the category category = Category() # Add attributes category.name = 'python' category.description = 'The Python programming language' category.slug = 'python' # Save it category.save() # Check we can find it all_categories = Category.objects.all() self.assertEquals(len(all_categories), 1) only_category = all_categories[0] self.assertEquals(only_category, category) # Check attributes self.assertEquals(only_category.name, 'python') self.assertEquals(only_category.description, 'The Python programming language') self.assertEquals(only_category.slug, 'python')