Я не понимаю тесты в Джанго, не могли бы вы мне помочь, пожалуйста? - PullRequest
3 голосов
/ 07 декабря 2011

Я испытываю трудности с тестами в Django и Python, для своего финального проекта я делаю сайт для форумов, но на самом деле я понятия не имею, как и какими должны быть мои тесты.Вот страница просмотров из файла mysite.Может кто-нибудь, пожалуйста, проведите меня через то, что я должен проверить кроме того, если пользователь вошел в систему.

from django.core.urlresolvers import reverse
from settings import MEDIA_ROOT, MEDIA_URL
from django.shortcuts import redirect, render_to_response
from django.template import loader, Context, RequestContext
from mysite2.forum.models import *

def list_forums(request):
     """Main listing."""
     forums = Forum.objects.all()
     return render_to_response("forum/list_forums.html", {"forums":forums},      context_instance=RequestContext(request))



def mk_paginator(request, items, num_items):
    """Create and return a paginator."""
    paginator = Paginator(items, num_items)
    try: page = int(request.GET.get("page", '1'))
    except ValueError: page = 1

    try:
        items = paginator.page(page)
    except (InvalidPage, EmptyPage):
        items = paginator.page(paginator.num_pages)
    return items


def list_threads(request, forum_slug):
    """Listing of threads in a forum."""
    threads = Thread.objects.filter(forum__slug=forum_slug).order_by("-created")
    threads = mk_paginator(request, threads, 20)
     template_data = {'threads': threads} 
    return render_to_response("forum/list_threads.html", template_data, context_instance=RequestContext(request))

def list_posts(request, forum_slug, thread_slug):
    """Listing of posts in a thread."""
    posts = Post.objects.filter(thread__slug=thread_slug,  thread__forum__slug=forum_slug).order_by("created")
    posts = mk_paginator(request, posts, 15)
    thread = Thread.objects.get(slug=thread_slug)
    template_data = {'posts': posts, 'thread' : thread}
    return render_to_response("forum/list_posts.html", template_data, context_instance=RequestContext(request))

def post(request, ptype, pk):
    """Display a post form."""
    action = reverse("mysite2.forum.views.%s" % ptype, args=[pk])
    if ptype == "new_thread":
        title = "Start New Topic"
        subject = ''
    elif ptype == "reply":
        title = "Reply"
        subject = "Re: " + Thread.objects.get(pk=pk).title
    template_data = {'action': action, 'title' : title, 'subject' : subject}

    return render_to_response("forum/post.html", template_data, context_instance=RequestContext(request))

def new_thread(request, pk): 
    """Start a new thread."""
    p = request.POST
    if p["subject"] and p["body"]:
        forum = Forum.objects.get(pk=pk)
        thread = Thread.objects.create(forum=forum, title=p["subject"], creator=request.user)
        Post.objects.create(thread=thread, title=p["subject"], body=p["body"], creator=request.user)
     return HttpResponseRedirect(reverse("dbe.forum.views.forum", args=[pk]))

def reply(request, pk):
    """Reply to a thread."""
     p = request.POST
    if p["body"]:
        thread = Thread.objects.get(pk=pk)
        post = Post.objects.create(thread=thread, title=p["subject"],         body=p["body"],
        creator=request.user)
     return HttpResponseRedirect(reverse("dbe.forum.views.thread", args=[pk]) +      "?page=last")

Ответы [ 2 ]

3 голосов
/ 07 декабря 2011

Сначала прочитайте документацию по тестированию Django .Вы также можете прочитать эту книгу .В некоторых областях оно датировано, но тестирование по-прежнему почти такое же, как и в 1.1.

Это немного большая тема для ответа в SO-ответе.

1 голос
/ 07 декабря 2011

Ну, вы можете проверить:

  • Если у вас есть правильное количество страниц для разбивки на страницы.
  • Если просматриваемая страница содержит правильныедиапазон объекта.Если при попытке доступа к несуществующей странице возвращается соответствующая ошибка.
  • Если при просмотре списков объектов и сведений об объекте возвращается правильный код состояния HTTP (200)

Длязакуска.Надеюсь, это поможет вам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...