Django框架测试功能不工作

2ekbmq32  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(113)

我一直停留在这个功能得到这个错误,我似乎不能解决,我仍然是新的编码。它给我错误的事情,我觉得我已经做了。
我有很多文件,但我会分享我最近刚刚更改的文件,我认为这一定是问题所在。
这是我的账户/views.py:

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.urls import reverse
from .forms import LoginForm

def login_view(request):
    if request.method == "GET":
        form = LoginForm()
        return render(request, "accounts/login.html", {"form": form})
    elif request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect(reverse("projects:list_projects"))
    return redirect(reverse("accounts:login"))

这是我的帐户/urls.py:

from django.urls import path
from . import views

app_name = "accounts"

urlpatterns = [
    path("login/", views.login_view, name="login"),
]

这是我的accounts/templates/accounts/login.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Login</title>
  </head>
  <body>
    <main>
      <div>
        <h1>Login</h1>
      </div>
      <form method="post">
        {% csrf_token %} {{ form }}
        <button type="submit">Login</button>
      </form>
    </main>
  </body>
</html>

我读过我需要完成的事情的规则,感觉我已经达到了标准,但它给了我一个错误,好像我没有做到所有这些。
这是我得到的错误:

(env) PS  python manage.py test tests.test_feature_07
Found 9 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.FFFFEEE.
======================================================================
ERROR: test_login_fails_for_unknown_user (tests.test_feature_07.FeatureTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "", line 126, in test_login_fails_for_unknown_user
    reverse("login"),
  File "\env\lib\site-packages\django\urls\base.py", line 88, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "\env\lib\site-packages\django\urls\resolvers.py", line 828, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name.

======================================================================
ERROR: test_login_resolves_to_accounts_login (tests.test_feature_07.FeatureTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "", line 18, in test_login_resolves_to_accounts_login
    path = reverse("login")
  File "", line 88, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "\env\lib\site-packages\django\urls\resolvers.py", line 828, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name.

======================================================================
ERROR: test_login_works (tests.test_feature_07.FeatureTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "", line 115, in test_login_works
    reverse("login"),
  File "\env\lib\site-packages\django\urls\base.py", line 88, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "\env\lib\site-packages\django\urls\resolvers.py", line 828, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name.

======================================================================
FAIL: test_form_has_button (tests.test_feature_07.FeatureTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "\tests\test_feature_07.py", line 98, in test_form_has_button
    self.fail(
AssertionError: Did not find the form at the path html > body > main > div > form

======================================================================
FAIL: test_form_has_password_input (tests.test_feature_07.FeatureTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "\tests\test_feature_07.py", line 81, in test_form_has_password_input
    self.fail(
AssertionError: Did not find the form at the path html > body > main > div > form

======================================================================
FAIL: test_form_has_username_input (tests.test_feature_07.FeatureTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "\tests\test_feature_07.py", line 64, in test_form_has_username_input
    self.fail(
AssertionError: Did not find the form at the path html > body > main > div > form

======================================================================
FAIL: test_form_is_post (tests.test_feature_07.FeatureTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "\tests\test_feature_07.py", line 40, in test_form_is_post
    self.assertIsNotNone(
AssertionError: unexpectedly None : Did not find the form at the path html > body > main > div > form

----------------------------------------------------------------------
Ran 9 tests in 0.183s

FAILED (failures=4, errors=3)
Destroying test database for alias 'default'...

下面是该特定测试功能的代码:

from django.contrib.auth.models import User
from django.conf import settings
from django.test import TestCase, Client
from django.urls import reverse

from .utils import Document

class FeatureTests(TestCase):
    def setUp(self):
        self.client = Client()
        self.response = self.client.get("/accounts/login/")
        self.content = self.response.content.decode("utf-8")
        self.document = Document()
        self.document.feed(self.content)

    def test_login_resolves_to_accounts_login(self):
        path = reverse("login")
        self.assertEqual(
            path,
            "/accounts/login/",
            msg="Could not resolve path name 'login' to '/accounts/login/",
        )

    def test_accounts_login_returns_200(self):
        self.assertEqual(
            self.response.status_code,
            200,
            msg="Did not get the login page",
        )

    def test_page_has_fundamental_five(self):
        self.assertTrue(
            self.document.has_fundamental_five(),
            msg="The response did not have the fundamental five",
        )

    def test_form_is_post(self):
        form = self.document.select("html", "body", "main", "div", "form")
        self.assertIsNotNone(
            form,
            msg=(
                "Did not find the form at the path "
                "html > body > main > div > form"
            ),
        )
        if form:
            self.assertIn(
                "method",
                form.attrs,
                msg="Did not find 'method' for the form",
            )
            method = form.attrs.get("method")
            if method:
                self.assertEqual(
                    method.lower(),
                    "post",
                    msg="Form was not a post form",
                )

    def test_form_has_username_input(self):
        form = self.document.select("html", "body", "main", "div", "form")
        if not form:
            self.fail(
                "Did not find the form at the path html > body > main > div > form"
            )
        inputs = form.get_all_children("input")
        username = None
        for input in inputs:
            if input.attrs.get("name") == "username":
                username = input
                break
        self.assertIsNotNone(
            username,
            msg="Could not find the username input",
        )

    def test_form_has_password_input(self):
        form = self.document.select("html", "body", "main", "div", "form")
        if not form:
            self.fail(
                "Did not find the form at the path html > body > main > div > form"
            )
        inputs = form.get_all_children("input")
        password = None
        for input in inputs:
            if input.attrs.get("name") == "password":
                password = input
                break
        self.assertIsNotNone(
            password,
            msg="Could not find the password input",
        )

    def test_form_has_button(self):
        form = self.document.select("html", "body", "main", "div", "form")
        if not form:
            self.fail(
                "Did not find the form at the path html > body > main > div > form"
            )
        buttons = form.get_all_children("button")
        button = None
        for button in buttons:
            if button.inner_text().strip() == "Login":
                button = button
                break
        self.assertIsNotNone(
            button,
            msg="Could not find the 'Login' button",
        )

    def test_login_works(self):
        User.objects.create_user("noor", password="1234abcd.")
        response = self.client.post(
            reverse("login"),
            {"username": "noor", "password": "1234abcd."},
        )
        self.assertEqual(
            response.status_code,
            302,
            msg="Login does not seem to work",
        )

    def test_login_fails_for_unknown_user(self):
        response = self.client.post(
            reverse("login"),
            {"username": "noor", "password": "1234abcd."},
        )
        self.assertEqual(
            response.status_code,
            200,
            msg="Login does not seem to work",
        )

以防万一这是我的主要跟踪器/urls.py:

from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
    path("admin/", admin.site.urls),
    path(
        "projects/",
        include(("projects.urls", "projects"), namespace="projects"),
    ),
    path(
        "accounts/",
        include(("accounts.urls", "accounts"), namespace="accounts"),
    ),
    path("", views.redirect_to_projects, name="home"),
]

我在www.example.com中正确安装了所有应用程序settings.py

64jmpszr

64jmpszr1#

我认为你应该尝试在测试中进行这些更改:

  • reverse("login")更改为reverse("accounts:login");
  • self.document.select("html", "body", "main", "div", "form")更改为self.document.select("html", "body", "main", "form")

希望能有帮助!

相关问题