python - 测试带有 HTTP404 异常的视图函数
问题描述
我正在尝试测试此视图以确保它在 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
在管理面板中,您可以看到创建了多少链接以及点击了多少次 url。
#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 新手。谢谢
解决方案
假设您正在尝试编写测试函数
在这种情况下,您可以创建如下内容:
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
更多地阅读我在这里的内容将对测试有很大帮助
推荐阅读
- c - 在 C 中显示给定数组的每个组合
- file - 如何通过 Ansible 将 Git Repo 克隆到所有文件夹中
- database - 您将如何将来自 ex.:Windows 10 或 Steam 的许可证密钥存储在数据库中?
- react-native - 找不到符号“返回 CodePush.getJSBundleFile();” 反应原生
- flutter - 使用动态值与 arb 文件值匹配的 Flutter 国际化
- email - 在 google 工作区/套件中添加 list-unsubscribe 标头
- python - 反转嵌套列表以及python中的元素
- asp.net - 为什么我的 nuget 内容文件没有复制到我的 Web 应用程序?
- java - java.lang.ClassNotFoundException: com.mysql.cj.jdbc.MysqlDataSource
- python - 无法通过 Python 中的 SMTP 向 Outlook.com 发送邮件