Example #1
0
    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)
Example #2
0
    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')
Example #3
0
    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')
Example #4
0
    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])
Example #5
0
    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)
Example #6
0
    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)
Example #7
0
 def post(self):
     post_parser = reqparse.RequestParser()
     post_parser.add_argument('name',
                              type=str,
                              required=True,
                              help='the argument cannot be blank')
     post_parser.add_argument('article_ids',
                              type=int,
                              action='append',
                              help='the argument cannot be blank')
     args = post_parser.parse_args()
     try:
         category = Category()
         category.name = args['name']
         category.articles = [
             Article.query.get_or_404(id) for id in args['article_ids']
         ] if args['article_ids'] else []
         db.session.add(category)
         db.session.commit()
     except sqlalchemy.exc.IntegrityError:
         db.session.rollback()
         return {'status': 400, 'msg': '字段冲突'}, 400
     except sqlalchemy.exc.InvalidRequestError:
         db.session.rollback()
         return {'status': 400, 'msg': '字段冲突'}, 400
     return {'status': 200, 'msg': '新建分类成功'}
Example #8
0
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')
Example #9
0
    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 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)
Example #11
0
    def test_article_get(self):
        r = self.client.get(self.url + '/article')
        self.assertEqual(r.status_code, 401)
        article = Article()
        article.title = 'title-test'
        article.slug = 'test'
        article.content = 'content ' * 20
        db.session.add(article)
        db.session.commit()
        r = self.client.get(self.url + '/article?slug=test')
        self.assertEqual(r.status_code, 401)

        tag = Tag()
        tag.name = 'tag'
        db.session.add(tag)
        category = Category()
        category.name = 'category'
        db.session.add(category)
        db.session.commit()
        article = Article()
        article.title = 'article'
        article.slug = 'slug'
        article.category = category
        article.content = 'content'
        article.tags = [tag]
        db.session.add(category)
        db.session.commit()
        r = self.client.get(self.url + '/article?slug=slug')
        self.assertEqual(r.status_code, 401)
Example #12
0
 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)
Example #13
0
    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')
Example #14
0
    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)
Example #15
0
 def setUp(self):
     self.app = create_app('test')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     self.client = self.app.test_client()
     tag = Tag()
     tag.name = 'tagx'
     db.session.add(tag)
     category = Category()
     category.name = 'categoryx'
     db.session.add(category)
     db.session.commit()
     article = Article()
     article.title = 'articlex'
     article.slug = 'slugx'
     article.category = category
     article.content = 'contentx'
     article.tags = [tag]
     db.session.add(category)
     db.session.commit()
     user = User()
     user.name = 'admin'
     user.password = '******'
     db.session.add(user)
     db.session.commit()
Example #16
0
 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)
Example #17
0
    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()
Example #18
0
    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)
Example #19
0
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')
Example #20
0
    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)
Example #21
0
    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()
Example #22
0
    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)
Example #23
0
 def test_category_get(self):
     r = self.client.get(self.url + '/category?name=a')
     self.assertEqual(r.status_code, 404)
     category = Category()
     category.name = 'a'
     db.session.add(category)
     db.session.commit()
     r = self.client.get(self.url + '/category?name=a')
     self.assertTrue('a' in r.get_data(as_text=True))
Example #24
0
    def POST(self):
        def check(cate):
            parent=cate.parent_cat
            skey=cate.key()
            while parent:
                if parent.key()==skey:
                    return False
                parent=parent.parent_cat
            return True

        action=self.param("action")
        name=self.param("name")
        slug=self.param("slug")
        parentkey=self.param('parentkey')
        key=self.param('key')


        vals={'action':action,'postback':True}

        try:

                if action=='add':
                    cat= Category(name=name,slug=slug)
                    if not (name and slug):
                        raise Exception(_('Please input name and slug.'))
                    if parentkey:
                        cat.parent_cat=Category.get(parentkey)

                    cat.put()
                    self.redirect('/admin/categories')

                    #vals.update({'result':True,'msg':_('Saved ok')})
                    #self.render2('views/admin/category.html',vals)
                elif action=='edit':

                        cat=Category.get(key)
                        cat.name=name
                        cat.slug=slug
                        if not (name and slug):
                            raise Exception(_('Please input name and slug.'))
                        if parentkey:
                            cat.parent_cat=Category.get(parentkey)
                            if not check(cat):
                                raise Exception(_('A circle declaration found.'))
                        else:
                            cat.parent_cat=None
                        cat.put()
                        self.redirect('/admin/categories')

        except Exception ,e :
            if cat.is_saved():
                cates=[c for c in Category.all() if c.key()!=cat.key()]
            else:
                cates= Category.all()

            vals.update({'result':False,'msg':e.message,'category':cat,'key':key,'categories':cates})
            self.render2('views/admin/category.html',vals)
Example #25
0
    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')
Example #26
0
 def test_categories(self):
     category = Category()
     category.name = 'c'
     category.articles = [Article.query.get(1)]
     db.session.add(category)
     db.session.commit()
     r = self.client.get(self.url + '/categories', )
     self.assertEqual(r.status_code, 200)
     text = r.get_data(as_text=True)
     self.assertTrue('name' in text and 'articles' in text)
Example #27
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.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)
Example #28
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)
Example #29
0
    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)
Example #30
0
 def test_category_delete(self):
     category = Category()
     category.name = 'a'
     db.session.add(category)
     db.session.commit()
     r = self.client.delete(
         self.url + '/category',
         data=json.dumps({'id': 1}),
         content_type='application/json',
         headers={"Authorization": "Bearer {}".format(self.get_token())})
     self.assertEqual(r.status_code, 200)
     self.assertTrue(Category.query.get(1) is None)
Example #31
0
def saveCategory():
    id = request.form.get('id', -1)
    name = request.form.get('name', '其他').strip()
    if id != -1 and Category.query.filter_by(id=id).first():
        category = Category.query.filter_by(id=id).first()
    else:
        category = Category()
    category.name = name
    Category.updated_at = datetime.now
    db.session.add(category)
    db.session.commit()
    return jsonify({"code": 200})
Example #32
0
    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:
Example #33
0
    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)
Example #34
0
    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])
Example #35
0
def blogs_type():
    """
    博客分类
    1、如果get请求,查询分类数据,遍历查询结果,移除'最新'的分类
    2、返回模板admin/blogs_type.html,categories
    3、如果post请求,获取参数,name,id(表示编辑已存在的分类)
    4、校验name参数存在
    5、如果id存在(即修改已有的分类),转成int,根据分类id查询数据库,校验查询结果,category.name = name
    6、实例化分类对象,保存分类名称,提交数据到数据库
    7、返回结果

    :return:
    """
    if request.method == 'GET':
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/blogs_type.html', errmsg='查询数据错误')
        categories_dict_list = []
        for category in categories:
            categories_dict_list.append(category.to_dict())
        # categories_dict_list.pop(0)
        data = {'categories': categories_dict_list}
        return render_template('admin/blogs_type.html', data=data)
    cname = request.json.get('name')
    cid = request.json.get('id')
    if not cname:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if cid:
        try:
            cid = int(cid)
            category = Category.query.get(cid)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='查询数据错误')
        if not category:
            return jsonify(errno=RET.NODATA, errmsg='未查询到分类数据')
        category.name = cname
    else:
        category = Category()
        category.name = cname
        db.session.add(category)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
    return jsonify(errno=RET.OK, errmsg='OK')
Example #36
0
 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()
Example #37
0
    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)
Example #38
0
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)
Example #39
0
    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')
Example #40
0
    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)
Example #41
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)
Example #42
0
    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)
Example #43
0
def categoryAdd(request):
    if request.method == "POST":
        name = request.POST.get("name")
        try:
            category = Category()
            category.name = name
            category.save()
            result = {
                "code": "1",
                "msg": "添加成功!",
            }
        except Exception as e:
            print(e)
            result = {
                "code": "0",
                "msg": "添加失败!",
            }
        return JsonResponse(result)
Example #44
0
    def test_validate_article(self):
        site = Site.objects.get_current().domain
        user = BlogUser.objects.get_or_create(email="*****@*****.**",
                                              username="******")[0]
        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()

        tag = Tag()
        tag.name = "nicetag"
        tag.save()

        article = Article()
        article.title = "nicetitle"
        article.body = "nicecontent"
        article.author = user
        article.category = category
        article.type = 'a'
        article.status = 'p'

        article.save()
        self.assertEqual(0, article.tags.count())
        article.tags.add(tag)
        article.save()
        self.assertEqual(1, article.tags.count())

        response = self.client.get(article.get_absolute_url())
        self.assertEqual(response.status_code, 200)

        response = self.client.get(tag.get_absolute_url())
        self.assertEqual(response.status_code, 200)

        response = self.client.get(category.get_absolute_url())
        self.assertEqual(response.status_code, 200)

        from DjangoBlog.spider_notify import SpiderNotify
        SpiderNotify.baidu_notify([article.get_full_url()])
Example #45
0
    def test_validate_comment(self):
        site = Site.objects.get_current().domain
        user = BlogUser.objects.create_superuser(
            email="*****@*****.**",
            username="******",
            password="******")

        self.client.login(username='******', password='******')

        category = Category()
        category.name = "categoryccc"
        category.created_time = datetime.datetime.now()
        category.last_mod_time = datetime.datetime.now()
        category.save()

        article = Article()
        article.title = "nicetitleccc"
        article.body = "nicecontentccc"
        article.author = user
        article.category = category
        article.type = 'a'
        article.status = 'p'
        article.save()

        commenturl = reverse('comments:postcomment',
                             kwargs={'article_id': article.id})

        response = self.client.post(commenturl, {'body': '123ffffffffff'})

        self.assertEqual(response.status_code, 200)

        article = Article.objects.get(pk=article.pk)
        self.assertEqual(len(article.comment_list()), 0)

        response = self.client.post(commenturl, {
            'body': '123ffffffffff',
            'email': user.email,
            'name': user.username
        })

        self.assertEqual(response.status_code, 302)

        article = Article.objects.get(pk=article.pk)
        self.assertEqual(len(article.comment_list()), 1)
Example #46
0
    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)
Example #47
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')
Example #48
0
def new_category():
    try:
        category = request.json.get('category')
        article_ids = request.json.get('articles')
    except AttributeError:
        abort(400)
    print(category)
    if category:
        try:
            articles = [Article.query.get(id) for id in article_ids]
        except BaseException:
            abort(400)
        try:
            c = Category()
            c.name = category
            c.articles = articles
            db.session.add(c)
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            return jsonify({'status': '400', 'msg': '分类名重复'}), 400
        return jsonify({'status': 200})
    return jsonify({'status': 404}), 404
Example #49
0
    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/blog/category/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 category deleted
        all_categories = Category.objects.all()
        self.assertEquals(len(all_categories), 0)
Example #50
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')
Example #51
0
    def test_create_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()

        self.client.login(username='******', password='******')

        response = self.client.get('/admin/blog/post/add/')
        self.assertEquals(response.status_code, 200)

        response = self.client.post('/admin/blog/post/add/', {
            'title': 'First Post',
            'text': 'My first post -yay',
            'pub_date_0': '2014-07-17',
            'pub_date_1': '11:41:03',
            'slug': 'first-post',
            # 'site': '1',
            'category': '1',
            'tags': '1'
        },
                                    follow=True
        )
        self.assertEquals(response.status_code, 200)

        self.assertTrue('added successfully' in response.content)

        # Check the new post is in the database
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)
Example #52
0
    def test_validate_article(self):
        site = Site.objects.get_current().domain
        user = BlogUser.objects.get_or_create(email="*****@*****.**",
                                              username="******")[0]
        user.set_password("systemsgt.cn")
        user.is_staff = True
        user.is_superuser = True
        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()

        tag = Tag()
        tag.name = "nicetag"
        tag.save()

        article = Article()
        article.title = "nicetitle"
        article.body = "nicecontent"
        article.author = user
        article.category = category
        article.type = 'a'
        article.status = 'p'

        article.save()
        self.assertEqual(0, article.tags.count())
        article.tags.add(tag)
        article.save()
        self.assertEqual(1, article.tags.count())

        response = self.client.get(article.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        from DjangoBlog.spider_notify import SpiderNotify
        SpiderNotify.notify(article.get_absolute_url())
        response = self.client.get(tag.get_absolute_url())
        self.assertEqual(response.status_code, 200)

        response = self.client.get(category.get_absolute_url())
        self.assertEqual(response.status_code, 200)

        response = self.client.get('/search', {'q': 'django'})
        self.assertEqual(response.status_code, 200)
        s = load_articletags(article)
        self.assertIsNotNone(s)

        p = Paginator(Article.objects.all(), 2)
        s = load_pagination_info(p.page(1), '', '')
        self.assertIsNotNone(s)

        p = Paginator(Tag.objects.all(), 2)
        s = load_pagination_info(p.page(1), '分类标签归档', 'tagname')
        self.assertIsNotNone(s)

        p = Paginator(BlogUser.objects.all(), 2)
        s = load_pagination_info(p.page(1), '作者文章归档', 'username')
        self.assertIsNotNone(s)

        p = Paginator(Category.objects.all(), 2)
        s = load_pagination_info(p.page(1), '分类目录归档', 'categoryname')
        self.assertIsNotNone(s)

        f = BlogSearchForm()
        f.search()
        self.client.login(username='******', password='******')
        from DjangoBlog.spider_notify import SpiderNotify
        SpiderNotify.baidu_notify([article.get_full_url()])
        rsp = self.client.get('/refresh/')
        self.assertEqual(rsp.status_code, 200)
        from blog.templatetags.blog_tags import gravatar_url, gravatar
        u = gravatar_url('*****@*****.**')
        u = gravatar('*****@*****.**')
Example #53
0
def parse_xml():
    et = ET.ElementTree(file='/home/jasper/Downloads/jasper.xml')
    root = et.getroot()
    user = User.objects.get(username='******')
    count = 1
    alias_re = re.compile(r'^[a-z|0-9|\-]+$')

    for channel in root.findall('channel'):
        for item in channel.findall('item'):
            title = item.find('title')
            post_name = item.find('{http://wordpress.org/export/1.2/}post_name')
            pubDate = item.find('pubDate')
            description = item.find('description')
            content = item.find('{http://purl.org/rss/1.0/modules/content/}encoded')
            categories = item.findall('category')
            tags = []
            category = Category()
            for ca in categories:
                if ca.attrib['domain'] == 'post_tag':
                    tags.append(ca.text)
                else:
                    try:
                        category = Category.objects.get(name=ca.text)
                    except Category.DoesNotExist:
                        category.name = ca.text
                        if alias_re.match(ca.attrib['nicename']):
                            category.alias = ca.attrib['nicename']
                        else:
                            category.alias = category.name
                        print category.alias
                        category.save()
            try:
                Post.objects.get(title=title.text)
                print title.text, 'already exist'
                continue
            except Post.DoesNotExist:
                pass 

            post = Post()
            post.title = title.text
            post.category = category 
            if alias_re.match(post_name.text):
                post.alias = post_name.text
            else:
                post.alias = title.text 
            print post.alias
            post.content = content.text
            post.content_html = content.text
            if not description.text:
                post.summary = content.text[:140]
            else:
                post.summary = description.text
            post.is_old = True
            post.tags = ','.join(tags)
            create_time = pubDate.text[:-6]
            tf = '%a, %d %b %Y %H:%M:%S'
            post.old_pub_time = datetime.strptime(create_time, tf)
            print post.old_pub_time
            post.author = user 
            try:
                post.save()
                print count, post
                count += 1
            except Exception, e:
                print e
    def test_validate_article(self):
        site = get_current_site().domain
        user = BlogUser.objects.get_or_create(email="*****@*****.**",
                                              username="******")[0]
        user.set_password("superstrongz")
        user.is_staff = True
        user.is_superuser = True
        user.save()
        response = self.client.get(user.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        response = self.client.get('admin/admin/logentry/')
        s = SideBar()
        s.sequence = 1
        s.name = 'test'
        s.content = 'test content'
        s.is_enable = True
        s.save()

        category = Category()
        category.name = "category"
        category.created_time = datetime.datetime.now()
        category.last_mod_time = datetime.datetime.now()
        category.save()

        tag = Tag()
        tag.name = "nicetag"
        tag.save()

        article = Article()
        article.title = "nicetitle"
        article.body = "nicecontent"
        article.author = user
        article.category = category
        article.type = 'a'
        article.status = 'p'

        article.save()
        self.assertEqual(0, article.tags.count())
        article.tags.add(tag)
        article.save()
        self.assertEqual(1, article.tags.count())

        for i in range(20):
            article = Article()
            article.title = "nicetitle" + str(i)
            article.body = "nicetitle" + str(i)
            article.author = user
            article.category = category
            article.type = 'a'
            article.status = 'p'
            article.save()
            article.tags.add(tag)
            article.save()
        response = self.client.get(article.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        from DjangoBlog.spider_notify import SpiderNotify
        SpiderNotify.notify(article.get_absolute_url())
        response = self.client.get(tag.get_absolute_url())
        self.assertEqual(response.status_code, 200)

        response = self.client.get(category.get_absolute_url())
        self.assertEqual(response.status_code, 200)

        response = self.client.get('/search', {'q': 'django'})
        self.assertEqual(response.status_code, 200)
        s = load_articletags(article)
        self.assertIsNotNone(s)

        rsp = self.client.get('/refresh')
        self.assertEqual(rsp.status_code, 302)

        self.client.login(username='******', password='******')
        rsp = self.client.get('/refresh')
        self.assertEqual(rsp.status_code, 200)

        response = self.client.get(reverse('blog:archives'))
        self.assertEqual(response.status_code, 200)

        p = Paginator(Article.objects.all(), 2)
        self.__check_pagination__(p, '', '')

        p = Paginator(Article.objects.filter(tags=tag), 2)
        self.__check_pagination__(p, '分类标签归档', tag.slug)

        p = Paginator(Article.objects.filter(author__username='******'),
                      2)
        self.__check_pagination__(p, '作者文章归档', 'superstrongz')

        p = Paginator(Article.objects.filter(category=category), 2)
        self.__check_pagination__(p, '分类目录归档', category.slug)

        f = BlogSearchForm()
        f.search()
        self.client.login(username='******', password='******')
        from DjangoBlog.spider_notify import SpiderNotify
        SpiderNotify.baidu_notify([article.get_full_url()])

        from blog.templatetags.blog_tags import gravatar_url, gravatar
        u = gravatar_url('*****@*****.**')
        u = gravatar('*****@*****.**')
Example #55
0
    def test_edit_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.author = author
        post.site = site
        post.save()
        post.tags.add(tag)
        post.save()

        # Log in
        self.client.login(username='******', password="******")

        # Edit the post
        response = self.client.post('/admin/blogengine/post/1/', {
            'title': 'My second post',
            'text': 'This is my second blog post',
            'pub_date_0': '2013-12-28',
            'pub_date_1': '22:00:04',
            'slug': 'my-second-post',
            'site': '1',
            'category': '1',
            'tags': '1'
        },
        follow=True
        )
        self.assertEquals(response.status_code, 200)

        # Check changed successfully
        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, 'My second post')
        self.assertEquals(only_post.text, 'This is my second blog post')
Example #56
0
    def test_validate_comment(self):
        site = get_current_site().domain
        user = BlogUser.objects.create_superuser(
            email="*****@*****.**",
            username="******",
            password="******")

        self.client.login(username='******', password='******')

        category = Category()
        category.name = "categoryccc"
        category.created_time = datetime.datetime.now()
        category.last_mod_time = datetime.datetime.now()
        category.save()

        article = Article()
        article.title = "nicetitleccc"
        article.body = "nicecontentccc"
        article.author = user
        article.category = category
        article.type = 'a'
        article.status = 'p'
        article.save()

        commenturl = reverse('comments:postcomment',
                             kwargs={'article_id': article.id})

        response = self.client.post(commenturl, {'body': '123ffffffffff'})

        self.assertEqual(response.status_code, 200)

        article = Article.objects.get(pk=article.pk)
        self.assertEqual(len(article.comment_list()), 0)

        response = self.client.post(commenturl, {
            'body': '123ffffffffff',
            'email': user.email,
            'name': user.username
        })

        self.assertEqual(response.status_code, 302)

        article = Article.objects.get(pk=article.pk)
        self.assertEqual(len(article.comment_list()), 1)
        parent_comment_id = article.comment_list()[0].id

        response = self.client.post(
            commenturl, {
                'body': '''
                                        # Title1  
        
        ```python
        import os
        ```  
        
        [url](https://www.lylinux.net/)  
          
        [ddd](http://www.baidu.com)  
        
        
        ''',
                'email': user.email,
                'name': user.username,
                'parent_comment_id': parent_comment_id
            })

        self.assertEqual(response.status_code, 302)

        article = Article.objects.get(pk=article.pk)
        self.assertEqual(len(article.comment_list()), 2)
        comment = Comment.objects.get(id=parent_comment_id)
        tree = parse_commenttree(article.comment_list(), comment)
        self.assertEqual(len(tree), 1)
        data = show_comment_item(comment, True)
        self.assertIsNotNone(data)
        s = get_max_articleid_commentid()
        self.assertIsNotNone(s)
Example #57
0
    def test_validate_article(self):
        site = Site.objects.get_current().domain
        user = BlogUser.objects.get_or_create(email="*****@*****.**", username="******")[0]
        user.set_password("liangliangyy")
        user.is_staff = True
        user.is_superuser = True
        user.save()
        response = self.client.get(user.get_absolute_url())
        self.assertEqual(response.status_code, 200)

        s = SideBar()
        s.sequence = 1
        s.name = 'test'
        s.content = 'test content'
        s.is_enable = True
        s.save()

        category = Category()
        category.name = "category"
        category.created_time = datetime.datetime.now()
        category.last_mod_time = datetime.datetime.now()
        category.save()

        tag = Tag()
        tag.name = "nicetag"
        tag.save()

        article = Article()
        article.title = "nicetitle"
        article.body = "nicecontent"
        article.author = user
        article.category = category
        article.type = 'a'
        article.status = 'p'

        article.save()
        self.assertEqual(0, article.tags.count())
        article.tags.add(tag)
        article.save()
        self.assertEqual(1, article.tags.count())

        for i in range(20):
            article = Article()
            article.title = "nicetitle" + str(i)
            article.body = "nicetitle" + str(i)
            article.author = user
            article.category = category
            article.type = 'a'
            article.status = 'p'
            article.save()
            article.tags.add(tag)
            article.save()
        response = self.client.get(article.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        from DjangoBlog.spider_notify import SpiderNotify
        SpiderNotify.notify(article.get_absolute_url())
        response = self.client.get(tag.get_absolute_url())
        self.assertEqual(response.status_code, 200)

        response = self.client.get(category.get_absolute_url())
        self.assertEqual(response.status_code, 200)

        response = self.client.get('/search', {'q': 'django'})
        self.assertEqual(response.status_code, 200)
        s = load_articletags(article)
        self.assertIsNotNone(s)

        rsp = self.client.get('/refresh')
        self.assertEqual(rsp.status_code, 302)

        self.client.login(username='******', password='******')
        rsp = self.client.get('/refresh')
        self.assertEqual(rsp.status_code, 200)

        response = self.client.get(reverse('blog:archives'))
        self.assertEqual(response.status_code, 200)

        p = Paginator(Article.objects.all(), 2)
        self.__check_pagination__(p, '', '')

        p = Paginator(Article.objects.filter(tags=tag), 2)
        self.__check_pagination__(p, '分类标签归档', tag.slug)

        p = Paginator(Article.objects.filter(author__username='******'), 2)
        self.__check_pagination__(p, '作者文章归档', 'liangliangyy')

        p = Paginator(Article.objects.filter(category=category), 2)
        self.__check_pagination__(p, '分类目录归档', category.slug)

        f = BlogSearchForm()
        f.search()
        self.client.login(username='******', password='******')
        from DjangoBlog.spider_notify import SpiderNotify
        SpiderNotify.baidu_notify([article.get_full_url()])

        from blog.templatetags.blog_tags import gravatar_url, gravatar
        u = gravatar_url('*****@*****.**')
        u = gravatar('*****@*****.**')
Example #58
0
    def test_create_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()

        # Set the attributes
        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)

        # Check attributes
        self.assertEquals(only_post.title, 'My first post')
        self.assertEquals(only_post.text, 'This is my first blog post')
        self.assertEquals(only_post.slug, 'my-first-post')
        self.assertEquals(only_post.site.name, 'example.com')
        self.assertEquals(only_post.site.domain, 'example.com')
        self.assertEquals(only_post.pub_date.day, post.pub_date.day)
        self.assertEquals(only_post.pub_date.month, post.pub_date.month)
        self.assertEquals(only_post.pub_date.year, post.pub_date.year)
        self.assertEquals(only_post.pub_date.hour, post.pub_date.hour)
        self.assertEquals(only_post.pub_date.minute, post.pub_date.minute)
        self.assertEquals(only_post.pub_date.second, post.pub_date.second)
        self.assertEquals(only_post.author.username, 'testuser')
        self.assertEquals(only_post.author.email, '*****@*****.**')
        self.assertEquals(only_post.category.name, 'python')
        self.assertEquals(only_post.category.description, 'The Python programming language')

        # Check tags
        post_tags = only_post.tags.all()
        self.assertEquals(len(post_tags), 1)
        only_post_tag = post_tags[0]
        self.assertEquals(only_post_tag, tag)
        self.assertEquals(only_post_tag.name, 'python')
        self.assertEquals(only_post_tag.description, 'The Python programming language')