Example #1
0
    def test_link_to_post_present(self):
        post = Post(title=u"Post 1")
        post.put()

        response = self.client.get(self.url)

        self.assertContains(response, post.url)
Example #2
0
    def test_post_by_slug(self):
        post = Post(title=u"New post")
        post.put()

        by_slug = Post.get_by_slug("new-post")

        self.assertEquals(by_slug, post)
Example #3
0
  def process(self):
    self.log("Starting to process key: " + self.key)
    data = self._getData()
    post = self._getExistingPost()

    if not post:
      self.log("Post has not been seen before, creating new one.")
      post = Post()
      post.date_published = self._getPublishedDate()
      post.key = ndb.Key("Post", self.subkey)
      post.slug = data.get('slug', self.slug)
      post.published = True
    else:
      self.log("Post has been seen before, updating existing one.")

    # As a precaution, if the post has a status that is draft, ignore it.
    if data.get('status'):
      if data['status'] == "draft":
        self.log("Caught post in Draft mode, ending processing.")
        return

    post.title = data['title']
    post.body = self._renderBody(data.content)
    post.frontmatter = data.to_dict()
    post.put()

    return post.body
Example #4
0
    def post(self, request, slug=None, *args, **kwargs):
        if not users.is_current_user_admin():
            return HttpResponseForbidden()

        post = self.get_object()
        if not post and slug:
            raise Http404()

        form = PostForm(request.POST)
        if not form.validate():
            error_msg = [
                "There are problems with the form:",
            ]
            error_msg = itertools.chain(error_msg, *form.errors.values())

            return HttpResponseBadRequest("<br/>".join(error_msg))

        # title has to exit at that point due to the validators
        new_slug = slugify(form.data["title"])
        if slug is None and Post.get_by_slug(new_slug):
            return HttpResponseBadRequest("Post with this title alread exit")

        created = False
        if not post:
            created = True
            post = Post()

        form.populate_obj(post)
        post.author = users.get_current_user().nickname()
        post.put()

        context = self.get_context_data(post=post, short=created)
        return self.render_to_response(context)
Example #5
0
def add():
    form = PostForm(request.form)
    if request.method == "POST" and form.validate():
        post = Post(title=form.title.data, slug=form.slug.data, content=form.content.data)
        post.put()
        return redirect(post.get_url())
    return render_template("form.html", form=form, section="add")
Example #6
0
    def test_loggedin_user(self):
        self.users_login('someone@localhost', is_admin=False)
        post = Post(title=u"Post 1")
        post.put()

        response = self.client.get(post.url)

        self.assertNotContains(response, "Edit post")
        self.assertNotContains(response, "Delete")
        self.assertNotContains(response, "form")
Example #7
0
    def test_basic_post_data(self):
        post = Post()
        post.title = u"Some interesting post"
        post.body = "ABC" * 1000
        post.author = "Owner of blog"
        post.put()

        response = self.client.get(post.url)

        self.assertContains(response, post.title)
        self.assertContains(response, post.body)
        self.assertContains(response, "Written by Owner of blog")
Example #8
0
    def test_loggedin_admin(self):
        self.users_login('owner@localhost', is_admin=True)
        post = Post(title=u"Post 1")
        post.put()

        response = self.client.get(post.url)

        self.assertContains(response, "Edit post")
        self.assertContains(response, "Delete")

        # form has no action url - post to it self
        self.assertNotContains(response, "action")
Example #9
0
    def test_body_of_post_is_truncated(self):
        post = Post(title=u"Long post")
        post.body = "ABC " * 123
        post.put()
        expected_body = (
            "ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC "
            "ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC "
            "ABC ABC A..."
        )

        response = self.client.get(self.url)
        self.assertContains(response, expected_body)
Example #10
0
def _create_test_post(slug, time_delta):
    from google.appengine.ext import db
    from django.contrib.webdesign import lorem_ipsum
    from datetime import datetime

    p = Post(
        title="Happy happy",
        body=(2 * "\n").join(lorem_ipsum.paragraphs(4)),
        # user          = users.get_current_user(),
        tags=[db.Category("bonners"), db.Category("cheese"), db.Category("weiners")],
        slug=slug,
        published_at=datetime.fromtimestamp(1282380470 - time_delta),
    )
    p.put()
Example #11
0
def create(request):
    if request.method == 'POST':
        title = request.POST['title']
        body = request.POST['body']

        post = Post(title=title, body=body)
        post.put()

        post_id = post.id()
        title_for_url = post.title_for_url()
        year = post.created_at.year
        month = post.created_at.month
        redirect_uri = '/' + str(year) + '/' + str(month) + '/' + str(title_for_url) + '/' + str(post_id)

        return HttpResponseRedirect(redirect_uri)
    else:
        return render_to_response('create.html',
                                  {},
                                  context_instance=RequestContext(request))
Example #12
0
class TestDeletePostApi(AppEngineTestCase):

    def setUp(self):
        self.post = Post(title=u"Some interesting post")
        self.post.put()

    def test_no_user(self):
        response = self.client.delete(self.post.url)

        self.assertEquals(response.status_code, 403)

    def test_some_user(self):
        self.users_login('someone@localhost', is_admin=False)

        response = self.client.delete(self.post.url)

        self.assertEquals(response.status_code, 403)

    def test_admin_user(self):
        """
        Happy path:
        - Owner logged in
        """

        self.users_login('owner@localhost', is_admin=True)

        del_response = self.client.delete(self.post.url)
        get_response = self.client.get(self.post.url)

        self.assertEquals(del_response.status_code, 204)
        self.assertEquals(get_response.status_code, 404)

    def test_admin_user_incorrect_url(self):
        self.users_login('owner@localhost', is_admin=True)

        response = self.client.delete(reverse("blog_post", args=["some-slug"]))

        self.assertEquals(response.status_code, 404)
Example #13
0
def editPost(request, slug=None):
    """
    Admin interface for creating and editing blog posts.
    
    Parameters:
    - `request`: a `WSGIRequest` representing the HTTP request for this view
    - `slug`: the URL slug of the post to edit, or None to create a new post
    """
    ## This view function handles post creation, editing, deletion and display
    ## of edit interfaces
    # Create a list of success messages to be updated
    successes = []
    # If no URL slug is provided, it's a new blog post
    isNewPost = slug is None
    # If it's a new post, create an empty instance to play with; this will only
    # be written to the database if data has been submitted
    if isNewPost:
        post = None
    # If not a new post, try to get the blog post with the provided slug
    if not isNewPost:
        post = Post.all().filter("slug =", slug).get()
        if not post:
            raise Http404
    # If there's POST data, changes have been submitted so create/update the
    # post
    if request.method == "POST":
        # Parse the POST data with the form then store validated fields
        form = PostEditForm(request.POST)
        if form.is_valid():
            # Create a post instance using the validated form data
            # Only set the publish date and slug if this is a new post; these
            # can't be changed afterwards
            if isNewPost:
                post = Post(
                    content=form.cleaned_data["content"],
                    title=form.cleaned_data["title"],
                    summary=form.cleaned_data["summary"],
                    slug=getUniquePostSlug(form.cleaned_data['title']),
                    pubDate=datetime.datetime.now(),
                    lastMod=datetime.datetime.now(),
                )
            else:
                post.content = form.cleaned_data["content"]
                post.title = form.cleaned_data["title"]
                post.summary = form.cleaned_data["summary"]
            # Changes have only been made to instances in memory, so save to
            # database
            post.put()
            # Add a message to the success list
            successes.append(SUCCESS_POST_CREATED if isNewPost else \
                    SUCCESS_POST_UPDATED)
            #return redirect("blog:edit-post", slug=post.slug)
    else:
        # If not a new post, create a form bound to the instance grabbed earlier
        if not isNewPost:
            form = PostEditForm({
                    "content": post.content,
                    "title": post.title,
                    "summary": post.summary,
                    })
        # Otherwise create an unbound form to build the page with
        else:
            form = PostEditForm()
    # Render and return the edit form as a response
    return render_to_response(EDIT_POST_TEMPLATE, {'post': post, 'form': form,
            'successes': successes}, context_instance=RequestContext(request))
Example #14
0
class TestUpdatePostApi(AppEngineTestCase):

    def setUp(self):
        self.post = Post()
        self.post.title = u"Some interesting post"
        self.post.body = "some body"
        self.post.author = "Owner of blog"
        self.post.put()

    def test_no_user(self):
        data = {
            "title": "new title",
            "body": "new body",
        }

        response = self.client.post(self.post.url, data)

        self.assertEquals(response.status_code, 403)

    def test_some_user(self):
        self.users_login('someone@localhost', is_admin=False)
        data = {
            "title": "new title",
            "body": "new body",
        }

        response = self.client.post(self.post.url, data)

        self.assertEquals(response.status_code, 403)

    def test_admin_user(self):
        """
        Happy path:
        - Owner logged in
        - Full version of article in response
        - Post created as owner
        - Post actually updated (same timestamps)
        """

        self.users_login('owner2@localhost', is_admin=True)
        data = {
            "title": "new title",
            "body": "ABC" * 100,
        }

        response = self.client.post(self.post.url, data)
        updated_post = Post.get_by_slug("new-title")

        self.assertEquals(response.status_code, 200)
        self.assertContains(response, "new title")
        self.assertContains(response, "ABC" * 100)
        self.assertContains(response, "Written by owner2@localhost")
        self.assertEquals(updated_post.created_at, self.post.created_at)

    def test_admin_user_incorrect_url(self):
        self.users_login('owner@localhost', is_admin=True)
        data = {
            "title": "new title",
            "body": "ABC",
        }

        response = self.client.post(
            reverse("blog_post", args=["some-slug"]), data)

        self.assertEquals(response.status_code, 404)

    def test_missing_body(self):
        self.users_login('owner@localhost', is_admin=True)
        data = {
            "title": "some title",
        }

        response = self.client.post(self.post.url, data)

        self.assertContains(response, "Body is required", status_code=400)

    def test_values_empty(self):
        self.users_login('owner@localhost', is_admin=True)
        data = {
            "title": "",
            "body": "",
        }

        response = self.client.post(self.post.url, data)

        self.assertContains(response, "Title is required", status_code=400)
        self.assertContains(response, "Body is required", status_code=400)

    def test_values_missing(self):
        self.users_login('owner@localhost', is_admin=True)
        data = {
            # Empty data
        }

        response = self.client.post(self.post.url, data)

        self.assertContains(response, "Title is required", status_code=400)
        self.assertContains(response, "Body is required", status_code=400)