测试带有 HTTP404 异常的视图函数
Posted
技术标签:
【中文标题】测试带有 HTTP404 异常的视图函数【英文标题】:Test a view function with a HTTP404 exception 【发布时间】:2021-07-28 23:55:06 【问题描述】:我正在尝试测试此视图,以确保在 RedirectUrl 模型类不存在时它返回 HTTP404,如果存在则重定向到 destination_url。它还应该存储网址。 只是为了上下文,应用程序会收到一个这样的 url
www.xyz.com/redirect/1?whatsappid=12345
元刷新到
www.xyz.com/confirmredirect/1?whatsappid=12345
最后将查询参数传递给另一个站点
https://test_check.co.za/?whatsappid=12345
在管理面板中,您可以看到创建了多少个链接以及该网址被点击了多少次。
#Views.py
def clickActivity(request: HttpRequest, pk: int, whatsappid: int) -> HttpResponse:
try:
redirect_url = RedirectUrl.objects.get(id=pk)
except RedirectUrl.DoesNotExist:
raise Http404("No RedirectUrl matches the given query.")
store_url_entry = RedirectUrlsEntry(url=redirect_url)
store_url_entry.save()
destination_url = f"redirect_url.test_check_url" f"/?whatsappid=whatsappid"
return HttpResponseRedirect(destination_url)
#models.py
class RedirectUrl(models.Model):
url = models.URLField(
max_length=255,
blank=True,
null=True,
default="https://hub.momconnect.za/confirmredirect",
)
content = models.TextField(
default="This entry has no copy",
help_text="The content of the mesage that this link was sent in",
)
symptom_check_url = models.URLField(
max_length=200, null=False, blank=False, default="http://symptomcheck.co.za"
)
parameter = models.IntegerField(null=True, blank=True)
time_stamp = models.DateTimeField(auto_now=True)
def my_counter(self):
total_number = RedirectUrlsEntry.objects.filter(url=self.id).count()
return total_number
def __str__(self):
if self.url:
return (
f"self.parameter: self.url/self.id \n"
f"| Clicked self.my_counter() times | Content: self.content"
)
class RedirectUrlsEntry(models.Model):
url = models.ForeignKey(
RedirectUrl, on_delete=models.CASCADE, blank=True, null=True
)
time_stamp = models.DateTimeField(auto_now=True)
def __str__(self):
if self.url:
return (
f"self.url.url with ID self.url.id \n"
f"was visited at self.time_stamp"
)
#Urls.py
urlpatterns = [
path(
"confirmredirect/<int:pk>/<int:whatsappid>",
views.clickActivity,
name="ada_hook_redirect",
),
path("redirect/<int:pk>", views.default_page, name="ada_hook"),
]
我能够测试是否使用了正确的模板,但我正在为这个测试而苦苦挣扎。我是 Django 新手。谢谢
【问题讨论】:
【参考方案1】:假设您正在尝试编写测试函数
在这种情况下,您可以创建如下内容:
class MyTestCase(TestCase):
def test_redirecting_url(self):
# Use a test client
client = Client()
# tell it to go to the url
r = client.get(reverse('ada_hook', args=[pk]))
# assert that it redirected correctly
self.AssertRedirects(r, expected_url)
# if checking the status
assert r.status_code == 404
详细了解我在这里的内容将对测试有很大帮助
【讨论】:
以上是关于测试带有 HTTP404 异常的视图函数的主要内容,如果未能解决你的问题,请参考以下文章
django:通用类视图 + POST = HTTP 405(不允许的方法)